K-DigitalTraining 강의/1. Java
[3주차] 64. 날짜, 일자, 시간 정보를 원하는 포멧대로 출력하는 SimpleDateFormat클래스
이대곤
2022. 6. 2. 12:25
* 날짜 및 시간정보는 Calendar 클래스의 객체를 통해 얻을 수 있지만, Date 클래스의 객체를 통해서 얻을수도 있다.
단, SimpleDateFormat 클래스의 메소드가 인자로 Date 클래스 타입의 객체를 받고 있으므로
이를 사용하여 원하는 포멧대로 출력하고자 할 땐 Date 클래스와 함께 사용하자.
코드
import java.text.SimpleDateFormat;
import java.util.Date;
public class Ex08_09_Date {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now);
System.out.println(now.getMonth()+1 +"월");
System.out.println(now.getDate() +"일");
System.out.println(now.getDay()+1 +"요일"); // 요일 , 0:일, 1:월, 2:화,,, Calendar 클래스와 다르게 일요일이 0부터 시작됨.
System.out.println(now.getHours() + "시");
System.out.println();
//원하는 포맷대로 날짜 및 시간이 출력되게 하는 것
SimpleDateFormat sdf = new SimpleDateFormat("YY-MM-d"); // 포멧지정
System.out.println(sdf.format(now));// Date 객체의 값을 포멧대로 출력해주세요
System.out.println();
sdf = new SimpleDateFormat("YYYY년 MM월 dd일"); // MM대신 mm 을 넣으면 원하는 값이 아닌게 나오니 참고하자
System.out.println(sdf.format(now));
System.out.println();
sdf = new SimpleDateFormat("YYYY/MM/dd E요일 a hh:mm:ss");
System.out.println(sdf.format(now));
System.out.println();
}
}
실행결과
Tue May 31 12:14:53 KST 2022
5월
31일
3요일
12시
22-05-31
2022년 05월 31일
2022/05/31 화요일 오후 12:14:53