profile image

L o a d i n g . . .

 java.util 패키지

- 프로그램 개발에서 자주 사용되는 자료구조. 

- 날짜 정보를 제공해주는 유용한 API(Application Programming Interface) 포함

 

 

 

 


클래스 용도
Date 날짜와 시간 정보를 저장하는 클래스
Calendar  운영체제의 날짜와 시간을 얻을 때 사용

 

Date 클래스 

Date date = new Date();

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

 

Date 객체의 toString() 메소드는 날짜를 영문으로 리턴하기 때문에 원하는 형식의 날짜포맷은 SimpleDateFormat 클래스를 사용해야한다.

이후 format() 메소드를 호출해서 원하는 형식의 날짜 정보를 얻는다. (이 때 format()메소드의 매개값은 Date 객체사용)

 

public class DateEx {
	public static void main(String[] args) {
		Date now = new Date();
		String str = now.toString();
		System.out.println(str);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
		String str1 = sdf.format(now);
		System.out.println(str1);
	}
}

 

 

 

 

 

 

 


Calendar 클래스

Calendar now = Calendar.getInstance();

캘린더 클래스는 추상클래스이므로 new 연산자를 사용해서 인스턴스를 생성할 수 없다.

 

클래스 내 정적메소드인 getInstance() 메소드를 이용하여 현재 OS에 설정되어있는 TimeZone 기준으로 한 캘린더하위객체를 얻을 수 있다.

 

public class CalendarEx {
	public static void main(String[] args) {
		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH);
		int day = now.get(Calendar.DAY_OF_MONTH);
		
		int week = now.get(Calendar.DAY_OF_WEEK);
		String strWeek = null;
		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;
		default:
			strWeek = "일";
			break;
		}
		
		int amPm = now.get(Calendar.AM_PM);
		String strAmPm = null;
		if (amPm == Calendar.AM) {
			strAmPm = "오전";
		} else {
			strAmPm = "오후";
		}
		
		int hour = now.get(Calendar.HOUR);
		int min = now.get(Calendar.MINUTE);
		int sec = now.get(Calendar.SECOND);
		
		System.out.printf("%d년 %d월 %d일 %s요일 %s %d시 %d분 %d초", 
				year, month, day, strWeek, strAmPm, hour, min, sec);
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

참고 : 

- 혼자 공부하는 자바(신용권), 한빛미디어

 

반응형

'개발 > JAVA' 카테고리의 다른 글

[Java] 멀티 스레드2  (0) 2022.07.26
[Java] 멀티 스레드 1  (0) 2022.07.25
[Java] java.lang 패키지  (0) 2022.07.20
[Java] 예외처리  (0) 2022.07.18
[Java] 익명 객체  (0) 2022.07.13
복사했습니다!