2018년 3월 20일 화요일

[Java] Date String Parsing and Formatting


1. Parsing String to LocalDateTime with DateTimeFormatter


1
2
3
4
5
6
    static void parseStringToLocasDateTime() {
        String dateStr = "2018-03-20 13:54:26";
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
        LocalDateTime result = LocalDateTime.parse(dateStr, df);
        System.out.println(result);
    }


Result:
2018-03-20T13:54:26


2. Formatting LocalDateTime to String with DateTimeFormatter


1
2
3
4
5
6
7
    static void formatLocasDateTimeToString() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
        LocalDateTime date = LocalDateTime.now();  
        String dateStr = df.format(date);
        System.out.println(dateStr);
        System.out.println(date.toString());
    }


Result:
2018-03-29 22:22:23
2018-03-29T22:22:23.262


3. Parsing String to Date with SimpleDateFormat

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void parseStringToDate() {
        String dateStr = "2018-03-20 13:54:26";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        Date result;  
        try {
            result = df.parse(dateStr);
            System.out.println(result);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

Result:
Tue Mar 20 13:54:26 KST 2018


4. Formatting Date to String with SimpleDateFormat

1
2
3
4
5
6
7
void formatDateToString() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        Date date = new Date();  
        String dateStr = df.format(date);
        System.out.println(dateStr);
        System.out.println(date.toString());
    }

Result:
2018-03-21 01:25:45
Wed Mar 21 01:25:45 KST 2018


댓글 없음:

댓글 쓰기