LocalDateTime

AKMUPLAY·2023년 12월 5일
0

DO-SOPT-SERVER

목록 보기
2/3
post-thumbnail

지금까지 스프링 프로젝트를 진행하면서 생각보다 시간을 관리해야하는 상황이 많이 발생했었다.

그 때마다 LocalDate이나, LocalDateTime을 많이 활용했었는데 항상 시간에 쫓겨 개발하느라 제대로 이해하고 활용하지 못했다.

그래서 이 참에 LocalDateTime과 자주 사용하는 메서드에 대해 한 번 정리해보고자 한다.

LocalDateTime

우선 LocalDateTime은 LocalDate와 LocalTime을 합친 것이라고 생각하면 된다.

LocalDateTime 클래스에 들어가보면 LocalDateTime이 날짜를 나타내는 LocalDate와 시간을 나타내는 LocalTime으로 이루어져 있음을 확인할 수 있다.

참고로 LocalDate는 위와 같이 year, month, day로 이루어져있고,

LocalTime은 hour, minute, second, nano로 이루어져있다.

이제 내부 메서드를 살펴보자.

LocalDateTime.now()

Obtains the current date-time from the system clock in the default time-zone.

This will query the system clock in the default time-zone to obtain the current date-time.

Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

Returns:
the current date-time using the system clock and default time-zone, not null

위는 LocalDateTime 클래스에 적혀 있는 now() 메서드에 대한 설명이다.

현재 시간을 반환하는 메서드이다.

public static LocalDateTime now() {
        return now(Clock.systemDefaultZone());
    }

실제로 출력해본 값은 아래와 같다.

2023-12-05T17:33:30.320640900


LocalDateTime.of()

Obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.

This returns a LocalDateTime with the specified year, month, day-of-month, hour and minute. The day must be valid for the year and month, otherwise an exception will be thrown. The second and nanosecond fields will be set to zero.

Params:
year – the year to represent, from MIN_YEAR to MAX_YEAR
month – the month-of-year to represent, not null
dayOfMonth – the day-of-month to represent, from 1 to 31
hour – the hour-of-day to represent, from 0 to 23
minute – the minute-of-hour to represent, from 0 to 59

Returns:
the local date-time, not null

LocalDateTime.of()에 대한 설명이다.

위 메서드는 파라미터로 year, month, dayOfMonth, hour, minute는 공통적으로 가지며,
second와 nano는 지정해주지 않으면 기본값이 0으로 설정된다.

만약 유효하지 않은 날짜를 설정하면 오류를 던진다.

    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {
        LocalDate date = LocalDate.of(year, month, dayOfMonth);
        LocalTime time = LocalTime.of(hour, minute);
        return new LocalDateTime(date, time);
    }

참고로 Month는 Enum이며 JANUARY, FEBRUARY ...로 이루어져 있다.

상황에 맞게 다양한 파라미터로 메서드를 사용할 수 있다.

  • of(int year, Month month, int dayOfMonth, int hour, int minute)
  • of(int year, Month month, int dayOfMonth, int hour, int minute, int second)
  • of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
  • of(int year, int month, int dayOfMonth, int hour, int minute)
  • of(int year, int month, int dayOfMonth, int hour, int minute, int second)
  • of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
  • of(LocalDate date, LocalTime time)

LocalDateTime.parse()

Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30.

The string must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME.

Params:
text – the text to parse such as "2007-12-03T10:15:30", not null

Returns:
the parsed local date-time, not null

Throws:
DateTimeParseException – if the text cannot be parsed

LocalDateTime.parse()에 대한 설명이다.

주어진 문자열을 LocalDateTime 형식으로 파싱한다.

만약 파싱할 수 없으면 DateTimeParseException을 던진다.

public static LocalDateTime parse(CharSequence text) {
        return parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

기본형은 위와 같으며 아래와 같이 형식을 지정해줄 수도 있다.

    public static void main(String[] args) {
        String dateTimeString = "2023-12-05 10:15";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
    }

LocalDateTime.getYear() ~ LocalDateTime.getNano()

LocalDateTime에도 day, month, hour 등을 가져올 수 있는 get 메서드가 존재한다.
다른 get 메서드와 다를 건 없지만 아래 두 메서드를 살펴보자.

    public int getMonthValue() {
        return date.getMonthValue();
    }
    public Month getMonth() {
        return date.getMonth();
    }

위 두 메서드의 차이점은 무엇일까?

getMonthValue()는 LocalDateTime의 Month를 int형으로 가져오는 반면, getMonth()는 이를 Enum 형태인 Month로 가져온다.


LocalDateTime.plusYears() ~ LocalDateTime.plusNanos()

Returns a copy of this LocalDateTime with the specified number of years added.

This method adds the specified amount to the years field in three steps:

1. Add the input years to the year field
2. Check if the resulting date would be invalid
3. Adjust the day-of-month to the last valid day if necessary

For example, 2008-02-29 (leap year) plus one year would result in the invalid date 2009-02-29 (standard year). Instead of returning an invalid result, the last valid day of the month, 2009-02-28, is selected instead.

This instance is immutable and unaffected by this method call.

Params:
years – the years to add, may be negative

Returns:
a LocalDateTime based on this date-time with the years added, not null

Throws:
DateTimeException – if the result exceeds the supported date range

위는 plusYears()에 대한 Java의 설명이다.

LocalDateTime에 파라미터의 값만큼 더해준다.

아래 코드를 살펴보자.

    void test() {
        LocalDateTime time = LocalDateTime.of(2023, 12, 31, 23, 59);
        System.out.println(time.plusMonths(1));
    }

위 메서드를 출력해보면 다음과 같이 출력된다.

2024-01-31T23:59

값을 더해주면서 년도도 바뀌는 모습이다.

우리는 이를 통해 plus 메서드가 year, month, day 등도 고려해줌을 확인할 수 있다.

참고로 위 메서드는 윤년도 고려해준다.

아래 코드를 출력하면 다음과 같다.

    void test() {
        LocalDateTime time = LocalDateTime.of(2024, 2, 29, 23, 59);
        System.out.println(time.plusYears(1));
    }

2025-02-28T23:59

plus가 있으니 당연히 minus도 존재한다. 이는 생략하겠다.


LocalDateTime.isAfter()

Checks if this date-time is after the specified date-time.

This checks to see if this date-time represents a point on the local time-line after the other date-time.

LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
a.isAfter(b) == false
a.isAfter(a) == false
b.isAfter(a) == true

This method only considers the position of the two date-times on the local time-line. It does not take into account the chronology, or calendar system. This is different from the comparison in compareTo(ChronoLocalDateTime), but is the same approach as ChronoLocalDateTime.timeLineOrder().

Params:
other – the other date-time to compare to, not null

Returns:
true if this date-time is after the specified date-time

파라미터로 받는 값과 비교하여 이후인지 판별해준다.

성립한다면 true를, 틀리다면 false를 반환해준다.

    @Override  // override for Javadoc and performance
    public boolean isAfter(ChronoLocalDateTime<?> other) {
        if (other instanceof LocalDateTime) {
            return compareTo0((LocalDateTime) other) > 0;
        }
        return ChronoLocalDateTime.super.isAfter(other);
    }

LocalDateTime.isBefore()

Checks if this date-time is before the specified date-time.

This checks to see if this date-time represents a point on the local time-line before the other date-time.

LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
a.isBefore(b) == true
a.isBefore(a) == false
b.isBefore(a) == false

This method only considers the position of the two date-times on the local time-line. It does not take into account the chronology, or calendar system. This is different from the comparison in compareTo(ChronoLocalDateTime), but is the same approach as ChronoLocalDateTime.timeLineOrder().

Params:
other – the other date-time to compare to, not null

Returns:
true if this date-time is before the specified date-time

isBefore()또한 존재한다.

이전의 시간인지 판별해준다.

    @Override  // override for Javadoc and performance
    public boolean isBefore(ChronoLocalDateTime<?> other) {
        if (other instanceof LocalDateTime) {
            return compareTo0((LocalDateTime) other) < 0;
        }
        return ChronoLocalDateTime.super.isBefore(other);
    }

오늘은 LocalDateTime과 자주 쓰는 메서드에 대해 알아보았다.

클래스에 적힌 설명을 보며 공부해본 적이 사실상 처음인데 이해하는데 되게 큰 도움이 된다는 것을 알았다.

다른 클래스도 이러한 방식으로 공부해보아야겠다.

profile
우리가 노래하듯이, 우리가 말하듯이, 우리가 예언하듯이 살길

0개의 댓글