티스토리 뷰

자바 Java String to DateTime DateTime to String LocalDateTime 변환

public class DateTest {

    public static main(String[] args) throws ParseException {
        String dateTimeStr = "2022-07-20 09:30:25.123";
        String dateFormatPattern = "yyyy-MM-dd HH:mm:ss";

        // Date to String
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatPattern);
        Date date = dateFormat.parse(dateTimeStr);
        // Wed Jul 20 09:30:25 KST 2022
        System.out.println(date.toString());

        // String to Date
        dateTimeStr = dateFormat.format(date);
        // 2022-07-20 09:30:25
        System.out.println(dateTimeStr);

        // String to LocalDateTime
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormatPattern);
        LocalDateTime localDateTime = LocalDateTime.parse(dateTimeStr, dateTimeFormatter);
        String localDateTimeStr = localDateTime.toString();
        // 2022-07-20T09:30:25
        System.out.println(localDateTimeStr);
        localDateTimeStr = localDateTimeStr.replace("T", " ");
        // 2022-07-20 09:30:25
        System.out.println(localDateTimeStr);
    }

}

읽어주셔서 감사합니다.

댓글