날짜와 시간 - LocalDateTime

SungMin·2026년 5월 30일

자바 심화 정리

목록 보기
20/34

가장 기본이 되는 날짜와 시간 클래스는 LocalDate, LocalTime, LocalDateTime이 있다.

  • LocalDate: 날짜만 표현할 때 사용한다.
  • LocalTime: 시간만 표현할 때 사용한다.
  • LocalDateTime: 날짜와 시간 모두 표현할 때 사용한다.

package time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class LocalDateTimeMain {
    public static void main(String[] args) {
        LocalDateTime nowDt = LocalDateTime.now();
        System.out.println("현재 날짜시간 = " + nowDt);
        LocalDateTime ofDt = LocalDateTime.of(2016, 8, 16, 8, 10, 1);
        System.out.println("지정 날짜시간 = " + ofDt);

        // 날짜와 시간 분리
        LocalDate localDate = ofDt.toLocalDate();
        LocalTime localTime = ofDt.toLocalTime();
        System.out.println("localDate = " + localDate);
        System.out.println("localTime = " + localTime);

        // 날짜와 시간 합체
        LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
        System.out.println(localDateTime);

        // 계산(불변)
        LocalDateTime ofDtPlus = ofDt.plusDays(1000);
        System.out.println("지정 날짜시간 + 1000일: " + ofDtPlus);
        LocalDateTime ofDtYear = ofDt.plusYears(1);
        System.out.println("지정 날짜시간 + 1년: " + ofDtYear);

        // 비교
        System.out.println("현재 날짜시간이 지정날짜시간보다 이전인가? " + nowDt.isBefore(ofDt));
        System.out.println("현재 날짜시간이 지정날짜시간보다 이후인가? " + nowDt.isAfter(ofDt));
        System.out.println("현재 날짜시간이 지정날짜시간과 동일한가? " + nowDt.isEqual(ofDt));
    }
}
  • now() 메서드는 현재 시점을 출력한다.
  • of() 메서드는 특성 시점을 출력한다.

불변

모든 날짜 클래스는 불변이다.
따라서 변경이 될 경우 새로운 객체를 생성해서 반환하므로 반환값을 꼭 받아야 한다.


isEquals() vs equals()

  • isEquals()는 단순 비교대상이 시간적으로 같으면 true를 출력한다.
  • equals()는 객체의 타입, 타임존 등등 내부 데이터의 모든 구성요소가 같아야 true를 출력한다.
profile
오늘도 한 걸음씩 나아가

0개의 댓글