/ JAVAJUNGSUK

Ch10-13~16. SimpleDateFormat

자바의 정석 기초편

0. 목차



Chapter10. 날짜와 시간 & 형식화

Ch10 - 13. SimpleDateFormat

Ch10 - 14. SimpleDateFormat 예제1

Ch10 - 15. SimpleDateFormat 예제2

Ch10 - 16. SimpleDateFormat 예제3



Ch10 - 13. SimpleDateFormat


▶ SimpleDateFormat이란?

▷ 날짜와 시간을 다양한 형식으로 출력 가능
  • 날짜와 시간 → 다양한 형식 : format()
▷ 특정 형식으로 되어있는 문자열에서 날짜와 시간 출력 가능
  • 특정 형식 문자열 → 날짜와 시간 : parse()
▷ 날짜 관련 기호
<img src = "assets/built/postsImages/TheCornerstoneOfJava/2021-06-18-10cornerstoneJava5/img.png" width="100%"><br/>
▷ 시간 관련 기호




Ch10 - 14. SimpleDateFormat 예제1


yyyy-mm-dd hh:mm:ss 요일

▷ Date → 문자열 : format()
Date today = new Date();

SimpleDateFormat sdf;

sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E요일");

System.out.println(sdf.format(today));

// console
2021-07-28 15:05:48 수요일

2021 --D-→ 2022

▷ Date → 문자열 : format()
Date today = new Date();

SimpleDateFormat sdf;

sdf = new SimpleDateFormat("2021 --D-→ 2022");

System.out.println(sdf.format(today));

// console
2021 --209- 2022



Ch10 - 15. SimpleDateFormat 예제2


▶ 날짜와 시간 → 다양한 형식 : format()

yyyy-MM-dd
Date → format() → yyyy-MM-dd
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

String result = df.format(today);

System.out.println(result);

// console
2021-07-28



Ch10 - 16. SimpleDateFormat 예제3


▶ 특정 형식 문자열 → 날짜와 시간 : parse()

yyyy년 MM월 dd일 → yyyy/MM/dd
yyyy년 MM월 dd일 → parse() → Date → format() → yyyy/MM/dd
DateFormat df = new SimpleDateFormat("yyyy년 MM월 dd일");
DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd");

Date today = df.parse("2021년 7월 28일");

String result = df2.format(today);

System.out.println(result);

// console
2021/07/28