Java Category/Java

[JAVA] Date, Calendar, LocalDateTime 클래스 (날짜와 시간 클래스)

ReBugs 2023. 1. 24.

본 게시글은 혼자 공부하는 자바 (저자 : 신용권)의 책과 유튜브 영상을 참고하였고, 개인적으로 정리하는 글임을 알립니다.


클래스 설명
Date 날짜 정보를 전달하기 위해 사용
Calendar 다양한 시간대별로 날짜와 시간을 얻을 때 사용
LocalDateTime 날짜와 시간을 조작할 때 사용

 

Date 클래스

Date 클래스는 날짜를 표현하는 클래스이다. Date는 객체 간에 날짜 정보를 주고받을 때 매개변수나 리턴 타입으로 주로 사용된다.

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

SimpleDateFromat 생성자의 매개값은 형식 문자열이다. yyyy는 4자리 연도, MM은 2자리 월, dd는 2자리 일을 뜻한다.

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main{
	public static void main(String[] args) {
		Date now = new Date();
		String strNow1 = now.toString();		
		System.out.println(strNow1);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
		String strNow2 = sdf.format(now);
		System.out.println(strNow2);
	}
}
/*
Sun Jan 15 21:53:19 KST 2023
2023년 01월 15일 09시 53분 19초
*/

 

 

Calendar 클래스

Calendar 클래스는 달력을 표현한 클래스이다.

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

Calendar 클래스의 정적 메소드인 getInstance() 메소드를 이용하면 현재 운영체제에 설정되어 있는 시간대를 기준으로 한 Calendar 하위 객체를 얻을 수 있다.

import java.util.Calendar;

Calendar now = Calendar.getInstance();

int year = now.get(Calendar.YEAR); //연도를 리턴
int month = now.get(Calendar.MONTH)+1; //월을 리턴(0~11값이 리턴됨 그래서 +1을 해준 것임)
int day = now.get(Calendar.DAY_OF_MONTH); //일을 리턴
int week = now.get(Calendar.DAY_OF_WEEK);//요일을 리턴
int amPm = now.get(Calendar.AM_PM); //오전, 오후를 리턴
int hour = now.get(Calendar.HOUR); //시를 리턴
int minute = now.get(Calendar.MINUTE); //분을 리턴
int second = now.get(Calendar.SECOND); //초를 리턴

get() 메소드를 호출할 때 사용한 매개값은 모두 Calendar 클래스에 선언되어 있는 상수들이다.

 

예제 코드

import java.util.Calendar;
public class Main{
	public static void main(String[] args) {
Calendar now = Calendar.getInstance();
		
		int year    = now.get(Calendar.YEAR);                
		int month  = now.get(Calendar.MONTH) + 1;          
		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 = "일";
		}
		
		int amPm  = now.get(Calendar.AM_PM);   
		String strAmPm = null;
		if(amPm == Calendar.AM) {
			strAmPm = "오전";
		} else {
			strAmPm = "오후";
		}
		
		int hour    = now.get(Calendar.HOUR);                 
		int minute  = now.get(Calendar.MINUTE);             
		int second  = now.get(Calendar.SECOND);              

		System.out.print(year + "년 ");
		System.out.print(month + "월 ");
		System.out.println(day + "일 ");
		System.out.print(strWeek + "요일 ");
		System.out.println(strAmPm + " ");
		System.out.print(hour + "시 ");
		System.out.print(minute + "분 ");
		System.out.println(second + "초 ");
	}
}
/*
2023년 1월 15일 
일요일 오후 
10시 13분 52초 
*/

다른 시간대 얻기

Caleandar 클래스의 오버로딩된 다른 getInstance() 메소드를 이용하면 미국/로스엔젤레스와 같은 다른 시간대의 Calendar를 얻을 수 있다.

알고 싶은 시간대의 TimeZone 객체를 얻어, getInstance() 메소드의 매개값으로 넘겨주면 된다.

아래의 코드는 TimeZone 객체의 ID를 얻는 방법이다.

여기서 원하는 TimeZone 객체의 ID를 얻고 getInstance() 메소드의 매개값으로 넘겨주면 된다.

import java.util.TimeZone;
public class PrintTimeZoneID {
	public static void main(String[] args) {
		String[] availableIDs = TimeZone.getAvailableIDs();
		for(String id : availableIDs) {
			System.out.println(id);
		}
	}
}
/*
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
Africa/Brazzaville
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
....
....
엄청 많다.
*/

 

아래의 코드는 로스엔젤레스의 TimeZone 객체의 ID를 getInstance() 메소드의 매개값으로 넘겨주는 예제이다.

import java.util.Calendar;
import java.util.TimeZone;

public class LosAngelesExample {
	public static void main(String[] args) {
		TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
		Calendar now = Calendar.getInstance( timeZone );

		int amPm = now.get(Calendar.AM_PM);
		String strAmPm = null;
		if(amPm == Calendar.AM) {
			strAmPm = "오전";
		} else {
			strAmPm = "오후";
		}
		int hour = now.get(Calendar.HOUR);
		int minute = now.get(Calendar.MINUTE);
		int second = now.get(Calendar.SECOND);

		System.out.print(strAmPm + " ");
		System.out.print(hour + "시 ");
		System.out.print(minute + "분 ");
		System.out.println(second + "초 ");
	}
}
/*
오전 8시 20분 44초
*/

 

 

날짜와 시간 비교

LocalDateTime 클래스는 날짜와 시간을 비교할 수 있는 아래의 메소드를 제공한다.

리턴 타입 메소드(매개변수) 설명
boolean isAfter(other) 이후 날짜인지?
isBefore(other) 이전 날짜인지?
isEqual(other) 동일 날짜인지?
long until(other, unit) 주어진 단위(unit) 차이를 리턴

 

아래의 예제는 현재 글쓰는 날의 다음날인 23.07.20 0시 0분 0초부터 24.12.31 0시 0분 0초까지를 계산하는 코드이다.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTimeCompareExample {
	public static void main(String[] args) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd a HH:mm:ss");

		LocalDateTime startDateTime = LocalDateTime.of(2023, 7, 20, 0, 0, 0);
		System.out.println("시작일: " + startDateTime.format(dtf));
		
		LocalDateTime endDateTime = LocalDateTime.of(2024, 12, 31, 0, 0, 0);
		System.out.println("종료일: " + endDateTime.format(dtf));
 
		if(startDateTime.isBefore(endDateTime)) {
			System.out.println("진행 중입니다.");
		} else if(startDateTime.isEqual(endDateTime)) {
			System.out.println("종료합니다.");
		} else if(startDateTime.isAfter(endDateTime)) {
			System.out.println("종료했습니다.");
		}
		
		long remainYear = startDateTime.until(endDateTime, ChronoUnit.YEARS);
		long remainMonth = startDateTime.until(endDateTime, ChronoUnit.MONTHS);
		long remainDay = startDateTime.until(endDateTime, ChronoUnit.DAYS);
		long remainHour = startDateTime.until(endDateTime, ChronoUnit.HOURS);
		long remainMinute = startDateTime.until(endDateTime, ChronoUnit.MINUTES);
		long remainSecond = startDateTime.until(endDateTime, ChronoUnit.SECONDS);
		System.out.println("남은 해: " + remainYear);
		System.out.println("남은 월: " + remainMonth);
		System.out.println("남은 일: " + remainDay);
		System.out.println("남은 시간: " + remainHour);
		System.out.println("남은 분: " + remainMinute);
		System.out.println("남은 초: " + remainSecond);
	}
}
/*
시작일: 2023.07.20 오전 00:00:00
종료일: 2024.12.31 오전 00:00:00
진행 중입니다.
남은 해: 1
남은 월: 17
남은 일: 530
남은 시간: 12720
남은 분: 763200
남은 초: 45792000
*/

댓글