본문 바로가기

JAVA

[ JAVA ] Date / Calendar - 날짜 사용하기

dl

 

 

 

자바 표준 API에는 날짜 정보와 관련된 클래스들이 있다. 

 

Date 클래스는 특정 시점의 날짜를 표현하는 클래스로 특정 시점의 연도, 월, 일, 시간 정보가 저장된다.

Calendar 클래스는 달력을 표현한 클래스로 해당 운영체제의 Calendar 객체를 얻으면 연도, 월, 일, 요일, 오전/오후, 시간 등의 정보를 얻을 수 있다..

 

 

 

 

 

Date 클래스

 

객체 간에 날짜 정보를 주고 받을 때 매개 변수나 리턴 타입으로 주로 사용된다. 

 

Date now = new Date();

인스턴스화하여 생성할 수 있고 Date 객체의 toString() 메소드는 영문으로 된 날짜를 리턴하기 때문에 원하는 날짜 형식의 문자열을 얻고 싶다면 java.text. 패키지의 SimpleDateFormat 클래스와 함께 사용하는 것이 좋다. 

 

SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");

SimpleDateFormat 생성자의 매개값은 문자열 형식이다. yyyy는 4자리 연도, MM은 2자리 월, dd는 2자리 일을 뜻한다. 문자열에 포함되는 기호는 API 도큐먼트의 SimpleDateFormat 클래스에서 찾을 수 있다. 

 

String strNow = sdf.format(now);

format() 메소드를 호출해 원하는 형식의 날짜 정보를 얻을 수 있다. format() 메소드의 매개값은 Date 객체이다.

 

System.out.println(strNow); // 2021년 07월 05일 04시 05분 08초

String strNow2 = now.toString();
System.out.println(strNow); // Mon Jul 05 16:05:08 KST 2021

 

 

 

 

Calendar 클래스

 

Calendar 클래스는 추상클래스라 new 연산자를 사용해 인스턴스를 생성할 수 없다. 그래서 클래스의 정적 메소드인 getInstance() 메소드를 이용하면 현재 운영체제에 설정되어 있는 시간대를 기준으로 한 Calendar 하위 객체를 얻을 수 있다. 

 

Calendar now = Calendar.getInstance();

 

Calendar 객체를 얻었다면 get() 메소드를 이용해 날짜와 시간에 대한 정보를 읽을 수 있다. 

 

int year = now.get(Calendar.YEAR); // 2021
int month = now.get(Calendar.MONTH) + 1; // 7
int day = now.get(Calendar.DAY_OF_MONTH); // 5

int week = now.get(Calendar.DAY_OF_WEEK);
String strWeek = "";
switch(week) {
		
	case Calendar.MONDAY:
		strWeek = "월";
		break;
	case Calendar.TUESDAY:
		strWeek = "화";
		break;
	case Calendar.WEDNESDAY:
		strWeek = "수";
		break;
	case Calendar.THURSDAY:
		strWeek = "목";
		break;
	case Calendar.FRIDAY:
		strWeek = "금";
		break;
	case Calendar.SATURDAY:
		strWeek = "토";
		break;
	case Calendar.SUNDAY:
		strWeek = "일";
		break;
}
System.out.println(strWeek + "요일");
        
        
int amPm = now.get(Calendar.AM_PM);
String strAmPm = "";
if(amPm == Calendar.AM) {
			
	strAmPm = "오전";
			
}else {
			
	strAmPm = "오후";
			
}
System.out.println(strAmPm);


int hour = now.get(Calendar.HOUR);
System.out.println(hour); // 4 (16시)

int minute = now.get(Calendar.MINUTE);
System.out.println(minute); // 5 (5분)
		
int second = now.get(Calendar.SECOND);
System.out.println(second); // 8 (8초)