JAVA

[JAVA] SimpleDateFormat

malang J 2023. 5. 15. 23:00

날짜와 시간을 다양한 형식으로 출력해준다.

 

▶ 기본
Date today = new Date();
SimpleFormat sdf = new SimpleFormat("yyyy-MM-dd");

String result = sdf.format(today); // 2023-05-15

 

▶ 날짜 기호

날짜

▶ 시간 기호

시간

 

public class SimpleDateFormatRun {
    public static void main(String[] args) {
        Date today = new Date(); // 현재의 날짜와 시간
        SimpleDateFormat sdf1, sdf2, sdf3, sdf4;
        SimpleDateFormat sdf5, sdf6, sdf7, sdf8, sdf9;

        sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf1.format(today)); // 2023-05-15

        sdf2 = new SimpleDateFormat("''yy년 MMM dd일 E요일");
        System.out.println(sdf2.format(today)); // 23년 5월 15일 월요일

        sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println(sdf3.format(today)); // 2023-05-15 22:28:04.622

        sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
        System.out.println(sdf4.format(today)); // 2023-05-15 22:28:04 오후
        System.out.println();

        sdf5 = new SimpleDateFormat("오늘은 올 해의 D번째 날이다.");
        System.out.println(sdf5.format(today)); // 135

        sdf6 = new SimpleDateFormat("오늘은 이 달의 d번째 날이다.");
        System.out.println(sdf6.format(today)); // 15

        sdf7 = new SimpleDateFormat("오늘은 올 해의 w번째 주이다.");
        System.out.println(sdf7.format(today)); // 20

        sdf8 = new SimpleDateFormat("오늘은 이 달의 W번째 주이다.");
        System.out.println(sdf8.format(today)); // 3

        sdf9 = new SimpleDateFormat("오늘은 이 달의 F번째 E요일이다.");
        System.out.println(sdf9.format(today)); // 3번째 월요일
    }
}

위는 날짜와 시간을 문자열로 바꾼 것이다.

 

문자열을 날짜와 시간으로 바꾸는 것도 가능하다.

public class SimpleFormatRun2 {
    public static void main(String[] args) {
        DateFormat df  = new SimpleDateFormat("yyyy년 MM월 dd일"); // 여기서 Date()로 먼저 바꿔야한다.
        DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");

        try{
            Date d = df.parse("2023년 05월 15일"); // 문자열 -> 날짜로
            System.out.println(df2.format(d)); // 날짜 -> 문자열
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}