개인 공부 내용 정리 목적입니다.
참고 : 자바의 정석(남궁성)
jdk 1.8부터 java.time 패키지가 추가 되었다.
Calendar는 날짜와 시간을 하나로 표현하였다.
java.time 패키지는 날짜와 시간을 별도의 클래스로 분리해 놓았다.
LocalTime : 시간 표현.
LocalDate : 날짜 표현.
LocalDateTime : 시간 + 날짜.
ZoneDateTime : LocalDateTime + 시간대
LocalDate loc = LocalDate.of(2019, 11,23);
LocalTime loct = LocalTime.of(23, 59,30);
LocalDateTime ldt = LocalDateTime.of(loc, loct);
ZonedDateTime zone = ZonedDateTime.now();
System.out.println(loc);
System.out.println(loct);
System.out.println(ldt);
System.out.println(zone);
//출력
2019-11-23
23:59:30
2019-11-23T23:59:30
2022-03-24T15:47:59.704+09:00[Asia/Seoul]
위에서 언급한 것처럼 java.time에서 객체를 생성하기 위해서 가장 기본적인 방법은 now()와 of()를 사용하는 것이다.
now()는 현재 날짜와 시간을 저장.
of() 사용자가 날짜와 시간을 조정한다.
위 클래스 4개 모두 이 2방식으로 생성 가능하다.
문자열 변환하기
LocalDate date = LocalDate.parse("1995-03-12");
LocalTime time = LocalTime.parse("12:59:30");
특정 필드값 가져오기
(LocalDate에서 월을 1~12 / 요일은 월:1 ~ 일:7 이다.)
LocalDate 주요 메서드
int getYear() //년도 반환
int getMonthValue() //월 반환
Month getMonth() // 월(November) .getValue()연달아 써야 숫자 월 반환
int getDayOfMonth() //해 기준 일
int getDayOfWeek() //요일 반환(Friday) .getValue()하면 숫자로 반환
int lengthOfMonth() //같은 달 총 일수
int lengOfYear() //같은 해 총 일수
boolean isLeapYear() //윤년 확인
LocalTime 주요 메서드
int getHour() //시 반환(24시간)
int getMinute() //분 반환
int getSecond() //초 반환
필드 값 변경하기
LocalDate withYear(int year);
LocalDate withMonth(int month);
LocalDate withDayOfMonth(int dayOfMonth);
LocalDate withDayOfYear(int dayOfYear);
LocalTime withHour(int hour):
LocalTime withMinute(int minute);
LocalTime withSecond(int second);
비교
compareTo()가 적절히 오버라이딩 되어있어 사용하기 편하다.
int result = 객체1.compareTo(객체2);
LocalTime의 경우 ()안의 값보다 이전이며 -1 , 같으면 0 , 이후면 1을 반환한다.
LocalDate의 경우 년도의 차이를 반환하고 ,
또 년도가 같으니까 월이 반환된다.
@Override
public int compareTo(ChronoLocalDate other) {
if (other instanceof LocalDate) {
return compareTo0((LocalDate) other);
}
return ChronoLocalDate.super.compareTo(other);
}
int compareTo0(LocalDate otherDate) {
int cmp = (year - otherDate.year);
if (cmp == 0) {
cmp = (month - otherDate.month);
if (cmp == 0) {
cmp = (day - otherDate.day);
}
}
return cmp;
}
코드를 살짝 들여다보니 , 이렇다.
CompareTo가 호출되면 , 그 코드가 내부적으로 compareTo0을 호출하는데 이때 보면 , 년도가 같으면 월을 비교하고 월이 같으면 일을 비교하여 반환한다.
그런데 이보다도 편하게 비교할 수 있는 메서드들이 추가로 제공된다.
//LocalDate 메서드에만 있다.
boolean isAfter(ChronoLocalDate other)
//other의 날짜가 이후면 true ,아니면 false
boolean isBefore(ChronoLocalDate other)
//other의 날짜가 이전이면 true ,아니면 false
boolean isEquals(ChronoLocalDate other)
여기서 isEquals는 연도를 제외한 날짜만을 비교한다.
equals는 연도까지 포함해서 비교한다.
LocalDateTime 생성 방법.
LocalDateTime date1 = LocalDateTime.of(2020,12,30,12,12,30);
LocalDateTime data2 = LocalDateTime.now();
LocalDate date = LocalDate.parse("1995-03-12");
LocalTime time = LocalTime.parse("12:59:30");
LocalDateTime date2 = LocalDateTime.of(data,time);
LocalDate 와 LocalTime으로 변환.
LocalDateTime date = LocalDateTime.of(1992,7,15,12,34,50);
LocalDate date2 = date.toLocalDate();
LocalTime date3 = date.toLocalTime();
이 밖에도 다양한 방식이 있다.
LocalDate에는 .atTime(LocalTime); 와 .atTime(23,11,11);
LocalTime에는 .atDate(LocalDate); 와 .atDate(2020,11,10);
해당 메소드들을 이용하여 날짜와 시간을 추가해줌으로써 LocalDateTime 객체로 반환되어질 수 있다.