헤르메스 LIFE

[날짜] LocalDate, Calendar, Date 날짜 가져오는 방법 본문

Core Java

[날짜] LocalDate, Calendar, Date 날짜 가져오는 방법

헤르메스의날개 2020. 12. 15. 10:26
728x90

출처 : docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

Date Format Pattern Syntax

You can design your own format patterns for dates and times from the list of symbols in the following table:

SymbolMeaningPresentationExample

G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

 

JDK1.8.x 부터 Date 를 사용하는 방법이 달라졌습니다.

 

    /**
     * 날짜를 원하는 SimpleDateFormat 에 맞춰 리턴한다.
     * 
     * @param strDate
     * @return
     */
    public static String getDateTimeFormat( String dateFormat ) {
        LocalDateTime nowDate = LocalDateTime.now();
        DateTimeFormatter formatter = null;
        String strDate = "";
        
        try {
            formatter = DateTimeFormatter.ofPattern(dateFormat);
        } catch(Exception e) {
            formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        }

        strDate = nowDate.format( formatter );
        
        return strDate;
    }

 

이전에 사용하던 방식 (JDK 1.1 기준)

    /**
     * 날짜를 원하는 SimpleDateFormat 에 맞춰 리턴한다.
     * 
     * @param strDate
     * @return
     */
    public static String getDateTimeFormat_( String dateFormat ) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat simpleDate = null;
        String strDate = "";
        
        try {
            simpleDate = new SimpleDateFormat(dateFormat);
        } catch(Exception e) {
            simpleDate = new SimpleDateFormat("yyyyMMddHHmmss");
        }

        strDate = simpleDate.format(cal.getTime());
        
        return strDate;
    }

 

이전에 사용하던 방식 (JDK 1.0 기준)

    /**
     * 날짜를 원하는 SimpleDateFormat 에 맞춰 리턴한다.
     * 
     * @param strDate
     * @return
     */
    public static String getDateTimeFormat_( String dateFormat ) {
        Date today = new Date();
        SimpleDateFormat simpleDate = null;
        String strDate = "";
        
        try {
            simpleDate = new SimpleDateFormat(dateFormat);
        } catch(Exception e) {
            simpleDate = new SimpleDateFormat("yyyyMMddHHmmss");
        }

        strDate = simpleDate.format(cal.getTime());
        
        return strDate;
    }

 

728x90