![[JAVA] Date, Calendar, LocalDateTime 클래스 (날짜와 시간 클래스)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FtjlJx%2FbtrWcroJypx%2F3VlMpRLsjHyn4KcjcitF10%2Fimg.jpg)
본 게시글은 혼자 공부하는 자바 (저자 : 신용권)의 책과 유튜브 영상을 참고하였고, 개인적으로 정리하는 글임을 알립니다.
클래스 | 설명 |
Date | 날짜 정보를 전달하기 위해 사용 |
Calendar | 다양한 시간대별로 날짜와 시간을 얻을 때 사용 |
LocalDateTime | 날짜와 시간을 조작할 때 사용 |
Date 클래스
- Date는 날짜를 표현하는 클래스로 객체 간에 날짜 정보를 주고받을 때 사용된다.
- Date 클래스에는 여러 개의 생성자가 선언되어 있지만 대부분 Deprecated(더 이상 사용되지 않음)되어 Date() 생성자만 주로 사용된다.
- Date() 생성자는 컴퓨터의 현재 날짜를 읽어 Date 객체로 만든다.
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 하위 객체를 얻을 수 있다.
Calendar가 제공하는 날짜와 시간에 대한 정보를 얻기 위해서는 get() 메소드를 이용한다.
get() 메소드의 매개값으로 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 클래스
날짜와 시간 조작
Date와 Calendar는 날짜와 시간 정보를 얻기에는 충분하지만, 날짜와 시간을 조작할 수는 없다.
이때는 java.time 패키지의 LocalDateTime 클래스가 제공하는 다음 메소드를 이용하면 매우 쉽게 날짜와 시간을 조작할 수 있다.
LocalDateTime 클래스를 이용해서 현재 컴퓨터의 날짜와 시간을 얻는 방법은 아래와 같다.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeOperationExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd a HH:mm:ss");
System.out.println("현재 시간: " + now.format(dtf));
LocalDateTime result1 = now.plusYears(1);
System.out.println("1년 덧셈: " + result1.format(dtf));
LocalDateTime result2 = now.minusMonths(2);
System.out.println("2월 뺄셈: " + result2.format(dtf));
LocalDateTime result3 = now.plusDays(7);
System.out.println("7일 덧셈: " + result3.format(dtf));
}
}
날짜와 시간 비교
LocalDateTime 클래스는 날짜와 시간을 비교할 수 있는 아래의 메서드도 제공한다.
비교를 위해 특정 날짜와 시간으로 LocalDateTime 객체를 얻는 방법은 아래와 같다.
year부터 second까지 매개값을 모두 int 타입 값으로 제공하면 된다.
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(2021, 1, 1, 0, 0, 0);
System.out.println("시작일: " + startDateTime.format(dtf));
LocalDateTime endDateTime = LocalDateTime.of(2021, 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);
}
}
'Language > Java' 카테고리의 다른 글
[JAVA] 자바 명명 규칙 (0) | 2023.07.03 |
---|---|
JavaSE, JDK, JRE 용어정리 (0) | 2023.06.23 |
[JAVA] Math 클래스(올림, 내림, 반올림, 절댓값, 난수 등) (0) | 2023.01.23 |
[JAVA]Wrapper(포장) 클래스 (0) | 2023.01.22 |
[JAVA] String 클래스 (0) | 2023.01.21 |