LocalDate
JAVA/Reference

LocalDate

public final class LocalDate extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable

A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a LocalDate.
This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.
The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of LocalDate may have unpredictable results and should be avoided. The equals method should be used for comparisons.
Implementation Requirements : This class is immutable and thread-safe.

 

시간을 제외한 날짜를 표현하는 불변 객체입니다. 재밌는 점은 LocalDate 객체는 어떤 시간대 정보도 저장하지 않는다는 것입니다. (do not store or represent a time or time-zone)

 

 

1. 필드

◎ MIN

public static final LocalDate MIN
The minimum supported LocalDate, '-999999999-01-01'. This could be used by an application as a "far past" date.

 

◎ MAX

public static final LocalDate MAX
The maximum supported LocalDate, '+999999999-12-31'. This could be used by an application as a "far future" date.

 

◎ EPOCH

public static final LocalDate EPOCH
The epoch year LocalDate, '1970-01-01'.

 

'1970-01-01'을 의미합니다.

 

 

 

 

2. 데이터 생성

◎ now

now( )

public static LocalDate now()
Obtains the current date 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. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
public static LocalDate now() {
    return now(Clock.systemDefaultZone());
}​

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

기본 시간대(DefaultZone)의 시스템 시계에서 현재 날짜를 가져오는 방식입니다.

하드 코딩되어 있기 때문에 테스트를 할 때는 주의해야 합니다.

 

now(ZoneId zone)

public static LocalDate now​(ZoneId zone)
Obtains the current date from the system clock in the specified time-zone.This will query the system clock to obtain the current date. Specifying the time-zone avoids dependence on the default time-zone.Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
public static LocalDate now(ZoneId zone) {
    return now(Clock.system(zone));
}​

Parameters : zone - the zone ID to use, not null
Returns : the current date using the system clock, not null

기본 시간대가 아닌 지정된 시간대의 시스템 시계에서 현재 날짜를 가져옵니다.

여기서 말하는 지정된 시간대는 ACT, AET, AGT, BST, VST, 등등... 을 말합니다.

 

now(Clock clock)

public static LocalDate now​(Clock clock)
Obtains the current date from the specified clock.This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using dependency injection.
public static LocalDate now(Clock clock) {
    Objects.requireNonNull(clock, "clock");
    final Instant now = clock.instant();  // called once
    return ofInstant(now, clock.getZone());
}

Parameters : clock - the clock to use, not null
Returns : the current date, not null

지정된 시스템 시계에서 현재 날짜를 가져옵니다.

 

 

 

◎ of

public static LocalDate of​(int year, Month month, int dayOfMonth)
Obtains an instance of LocalDate from a year, month and day.This returns a LocalDate with the specified year, month and day-of-month. The day must be valid for the year and month, otherwise an exception will be thrown.
public static LocalDate of(int year, Month month, int dayOfMonth) {
    YEAR.checkValidValue(year);
    Objects.requireNonNull(month, "month");
    DAY_OF_MONTH.checkValidValue(dayOfMonth);
    return create(year, month.getValue(), dayOfMonth);
}​

Parameters : 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
Returns : the local date, not null
Throws : DateTimeException - if the value of any field is out of range, or if the day-of-month is invalid for the month-year

제공받은 날짜들을 통해 LocalDate 인스턴스를 가져옵니다.

재밌는 점은 month 혼자 int가 아닌 Month 클래스라는 것입니다. 덕분에 내부 코드에서 보다시피 1~12월까지를 확인할 필요가 없습니다. 

추가적으로 month에 int를 사용할 수 있게 오버 로딩되어 있습니다. 내부적으로 검증을 거치기 때문에 부담 없이 사용해도 됩니다!

존재할 수 없는 날짜라면, DateTImeException을 던집니다.

 

 

 

◎ ofYearDay

public static LocalDate ofYearDay​(int year, int dayOfYear)
Obtains an instance of LocalDate from a year and day-of-year.This returns a LocalDate with the specified year and day-of-year. The day-of-year must be valid for the year, otherwise an exception will be thrown.
public static LocalDate ofYearDay(int year, int dayOfYear) {
    YEAR.checkValidValue(year);
    DAY_OF_YEAR.checkValidValue(dayOfYear);
    boolean leap = IsoChronology.INSTANCE.isLeapYear(year);
    if (dayOfYear == 366 && leap == false) {
        throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year");
    }
    Month moy = Month.of((dayOfYear - 1) / 31 + 1);
    int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
    if (dayOfYear > monthEnd) {
        moy = moy.plus(1);
    }
    int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
    return new LocalDate(year, moy.getValue(), dom);
}​

Parameters : year - the year to represent, from MIN_YEAR to MAX_YEAR
                  dayOfYear - the day-of-year to represent, from 1 to 366
Returns : the local date, not null
Throws : DateTimeException - if the value of any field is out of range, or if the day-of-year is invalid for the year

연도와, 1~365일을 가지고, LocalDate 인스턴스를 가져옵니다.

 

 

 

◎ ofInstant

public static LocalDate ofInstant​(Instant instant, ZoneId zone)
Obtains an instance of LocalDate from an Instant and zone ID.This creates a local date based on the specified instant. First, the offset from UTC/Greenwich is obtained using the zone ID and instant, which is simple as there is only one valid offset for each instant. Then, the instant and offset are used to calculate the local date.
public static LocalDate ofInstant(Instant instant, ZoneId zone) {
    Objects.requireNonNull(instant, "instant");
    Objects.requireNonNull(zone, "zone");
    ZoneRules rules = zone.getRules();
    ZoneOffset offset = rules.getOffset(instant);
    long localSecond = instant.getEpochSecond() + offset.getTotalSeconds();
    long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);
    return ofEpochDay(localEpochDay);
}​

Parameters : instant - the instant to create the date from, not nullzone - the time-zone, which may be an offset, not null
Returns : the local date, not null
Throws : DateTimeException - if the result exceeds the supported range
Since : 9

Instant 및 지정된 시간대(ZoneId)를 이용해 LocalDate의 인스턴스를 가져옵니다.

 

 

 

◎ ofEpochDay

public static LocalDate ofEpochDay​(long epochDay)
Obtains an instance of LocalDate from the epoch day count.This returns a LocalDate with the specified epoch-day. The EPOCH_DAY is a simple incrementing count of days where day 0 is 1970-01-01. Negative numbers represent earlier days.
public static LocalDate ofEpochDay(long epochDay) {
    EPOCH_DAY.checkValidValue(epochDay);
    long zeroDay = epochDay + DAYS_0000_TO_1970;
    // find the march-based year
    zeroDay -= 60;  // adjust to 0000-03-01 so leap day is at end of four year cycle
    long adjust = 0;
    if (zeroDay < 0) {
        // adjust negative years to positive for calculation
        long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1;
        adjust = adjustCycles * 400;
        zeroDay += -adjustCycles * DAYS_PER_CYCLE;
    }
    long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE;
    long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
    if (doyEst < 0) {
        // fix estimate
        yearEst--;
        doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
    }
    yearEst += adjust;  // reset any negative year
    int marchDoy0 = (int) doyEst;

    // convert march-based values back to january-based
    int marchMonth0 = (marchDoy0 * 5 + 2) / 153;
    int month = (marchMonth0 + 2) % 12 + 1;
    int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1;
    yearEst += marchMonth0 / 10;

    // check year now we are certain it is correct
    int year = YEAR.checkValidIntValue(yearEst);
    return new LocalDate(year, month, dom);
    }​

Parameters : epochDay - the Epoch Day to convert, based on the epoch 1970-01-01
Returns : the local date, not null
Throws : DateTimeException - if the epoch day exceeds the supported date range

'1970-01-01'를 기준으로 시작되는 epochDay를 통해 LocalDate의 인스턴스를 가져옵니다.

epochDay 변환된 시간
0 '1970-01-01'
10 '1970-01-11'

음수는 이전 날짜를 나타냅니다. 

 

 

◎ from

public static LocalDate from​(TemporalAccessor temporal)
Obtains an instance of LocalDate from a temporal object.This obtains a local date based on the specified temporal. A TemporalAccessor represents an arbitrary set of date and time information, which this factory converts to an instance of LocalDate.The conversion uses the TemporalQueries.localDate() query, which relies on extracting the EPOCH_DAY field.This method matches the signature of the functional interface TemporalQuery allowing it to be used as a query via method reference, LocalDate::from.
public static LocalDate from(TemporalAccessor temporal) {
    Objects.requireNonNull(temporal, "temporal");
    LocalDate date = temporal.query(TemporalQueries.localDate());
    if (date == null) {
        throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " +
            temporal + " of type " + temporal.getClass().getName());
    }
    return date;
}​

Parameters : temporal - the temporal object to convert, not null
Returns : the local date, not null
Throws : DateTimeException - if unable to convert to a LocalDateSee Also:Chronology.date(TemporalAccessor)

temporal 객체를 통해 LocalDate의 인스턴스를 리턴합니다.

TemporalAccessor는 임의의 날짜 및 시간 정보 세트를 나타냅니다. 변환은 EPOCH_DAY 필드 추출에 의존하는 TemporalQueries.localDate( ) 쿼리를 사용합니다. 이 메서드는 함수형 인터페이스의 시그니처와 동일합니다.

TemporalQuery를 사용하면 'LocalDate::from' 메서드 참조를 통해 쿼리로 사용할 수 있습니다.

 

 

◎ parse

public static LocalDate parse​(CharSequence text)
Obtains an instance of LocalDate from a text string such as 2007-12-03.The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.
public static LocalDate parse(CharSequence text) {
    return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
}​

Parameters : text - the text to parse such as "2007-12-03", not null
Returns : the parsed local date, not null
Throws : DateTimeParseException - if the text cannot be parsed

날짜와 시간 문자열로 LocalDate 인스턴스를 만드는 방법입니다.

기본적으로 ISO_LOCAL_DATE 방식인 "year-month-day"의 형태를 띠고 있으며,

다른 포맷으로 입력을 하고 싶다면, DateTimeFormatter을 입력하는 오버 로딩 parse를 이용합시다.

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, LocalDate::from);
}

 

 

3. 정보 가져오기

◎ range

public ValueRange range​(TemporalField field)
Gets the range of valid values for the specified field.The range object expresses the minimum and maximum valid values for a field. This date is used to enhance the accuracy of the returned range. If it is not possible to return the range, because the field is not supported or for some other reason, an exception is thrown.If the field is a ChronoField then the query is implemented here. The supported fields will return appropriate range instances. All other ChronoField instances will throw an UnsupportedTemporalTypeException.If the field is not a ChronoField, then the result of this method is obtained by invoking TemporalField.rangeRefinedBy(TemporalAccessor) passing this as the argument. Whether the range can be obtained is determined by the field.
public ValueRange range(TemporalField field) {
    if (field instanceof ChronoField) {
        ChronoField f = (ChronoField) field;
        if (f.isDateBased()) {
            switch (f) {
                case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
                case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
                case ALIGNED_WEEK_OF_MONTH: 
                    return ValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5);
                case YEAR_OF_ERA:
                    return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
            }
            return field.range();
        }
        throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
    }
    return field.rangeRefinedBy(this);
}​

Specified by : range in interface TemporalAccessor
Parameters : field - the field to query the range for, not null
Returns : the range of valid values for the field, not null
Throws : DateTimeException - if the range for the field cannot be obtained
            UnsupportedTemporalTypeException - if the field is not supported

LocalDate 인스턴스의 년, 월, 일에 대한 정확한 정보를 얻어야 하는 경우가 있습니다. 이렇게 파라미터에 대한 유효한 값의 범위를 가져오는 기능을 range에서 실시합니다.

 

2021년 9월 17일의 정보를 가지는 LocalDate 인스턴스에서, 정확하게 1일에서 며칠까지 있나 알아야 한다고 합시다.

// 2021년 9월은 1~30일 뿐
LocalDate date = LocalDate.of(2021, 9, 17);
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);	// 1 - 30
ValueRange range2 = date.range(ChronoField.MONTH_OF_YEAR);	// 1 - 12
ValueRange range3 = date.range(ChronoField.YEAR);		// -999999999 - 999999999

이런 경우 range(ChoronoField.DAY_OF_MONTH)를 사용하면 1 - 30으로 30일까지 있는 것을 알 수 있습니다.

나머지도 동일한 필드를 파라미터로 입력하면 정보를 얻을 수 있습니다.

 

 

 

◎ get

public int get​(TemporalField field)
Gets the value of the specified field from this date as an int. This queries this date for the value of the specified field. The returned value will always be within the valid range of values for the field. If it is not possible to return the value, because the field is not supported or for some other reason, an exception is thrown.
If the field is a ChronoField then the query is implemented here. The supported fields will return valid values based on this date, except EPOCH_DAY and PROLEPTIC_MONTH which are too large to fit in an int and throw an UnsupportedTemporalTypeException.
All other ChronoField instances will throw an UnsupportedTemporalTypeException.If the field is not a ChronoField, then the result of this method is obtained by invoking TemporalField.
getFrom(TemporalAccessor) passing this as the argument. Whether the value can be obtained, and what the value represents, is determined by the field.
public int get(TemporalField field) {
    if (field instanceof ChronoField) {
        return get0(field);
    }
    return ChronoLocalDate.super.get(field);
}​

Specified by : get in interface TemporalAccessor
Parameters : field - the field to get, not null
Returns : the value for the field
Throws : DateTimeException - if a value for the field cannot be obtained or the value is outside the range of
                                        valid values for the field
             UnsupportedTemporalTypeException - if the field is not supported or the range of values exceeds an int
             ArithmeticException - if numeric overflow occurs

지정된 필드의 값을 int로 가져오는 메서드입니다.

 

ChronoField 중 EPOCH_DAY, PROLEPTIC_MONTH의 경우와 지원하지 않는 필드(isSupported에서 false를 받는 필드)는 모두 UnsupportedTemporalTypeException를 발생시킵니다. 

LocalDate date = LocalDate.of(2021, 9, 17);
ChronoField clockHourOfDay = ChronoField.CLOCK_HOUR_OF_DAY;
ChronoField epochDay = ChronoField.EPOCH_DAY;

int i = date.get(ChronoField.DAY_OF_MONTH);	// 17

boolean supported1 = date.isSupported(epochDay);	// 지원은 하나 get에서 에러
int j = date.get(epochDay);	// UnsupportedTemporalTypeException

boolean supported2 = date.isSupported(clockHourOfDay);	// 지원X 필드
int k = date.get(clockHourOfDay); // UnsupportedTemporalTypeException

 

메서드 설명 예시 : 2021-9-17
get( ) 지원하는 필드에 한정해 필드의 값을 int로 가져옴
EPOCH_DAY, PROLEPTIC_MONTH 예외 발생
필드에 맞게 리턴
getLong( ) 지원하는 필드에 한정해 필드의 값을 Long로 가져옴 18887
getChronology( ) 해당 달력 시스템(연대기)을 가져옵니다. ISO
getEra( ) 기원전(BCE) / 기원후(CE)를 가져옵니다. (ISOEra 타입) CE (Common Era)
getYear( ) 연도를 int 타입에 맞게 가져옵니다. 2021
getMonthValue( ) 달을 int 타입에 맞게 가져옴 9
getMonth( ) 달을 Month 타입에 맞게 가져옴 SEPTEMBER
getDayOfMonth( ) 일(day)을 int 타입에 맞게 가져옴 17
getDayOfYear( ) 365일 기준으로 일(day)을 int 타입에 맞게 가져옴 260
getDayOfWeek( ) 요일을 DayOfWeek타입에 맞게 가져움 FRIDAY

 

 

◎ isLeapYear

public boolean isLeapYear( )
Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if it is divisible by four without remainder. However, years divisible by 100, are not leap years, with the exception of years divisible by 400 which are.For example, 1904 is a leap year it is divisible by 4. 1900 was not a leap year as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.The calculation is proleptic - applying the same rules into the far future and far past. This is historically inaccurate, but is correct for the ISO-8601 standard.
public boolean isLeapYear() {
    return IsoChronology.INSTANCE.isLeapYear(year);
}​

Specified by : i sLeapYear in interface ChronoLocalDate
Returns : true if the year is leap, false otherwise

윤년인지 확인하는 메서드입니다.

참고로 윤년은 년을 기준으로 4로 나누어 떨어지고, 100으로 나누어 떨어지지 않을 때 (단 400으로 나누어 떨어지는 것은 예외) 윤년입니다.

 

 

 

◎ lengthOfMonth, lengthOfYear

public int lengthOfMonth( )
Returns the length of the month represented by this date.This returns the length of the month in days. For example, a date in January would return 31.
public int lengthOfMonth() {
    switch (month) {
        case 2:
            return (isLeapYear() ? 29 : 28);
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;
        default:
            return 31;
    }
}​

Specified by : lengthOfMonth in interface ChronoLocalDate
Returns : the length of the month in days

public int lengthOfYear( )
public int lengthOfYear() {
    return (isLeapYear() ? 366 : 365);
}​

해당 달, 해당 연도의 일 수를 파악하는 메서드입니다.

메서드 설명
lengthOfMonth 달의 일 수를 반환 (28 or 29 or 30 or 31)
lengthOfYear 해의 총 일 수를 반환(윤년 - 366 or 365)

 

 

 

4. 데이터 가공

LocalDate라는 불변 클래스들을 변경을 해야 하는 경우에 사용되는 메서드들입니다.

◎ with(TemporalAdjuster adjuster)

public LocalDate with​(TemporalAdjuster adjuster)
Returns an adjusted copy of this date.
This returns a LocalDate, based on this one, with the date adjusted. The adjustment takes place using the specified adjuster strategy object. Read the documentation of the adjuster to understand what adjustment will be made.A simple adjuster might simply set the one of the fields, such as the year field. A more complex adjuster might set the date to the last day of the month.
A selection of common adjustments is provided in TemporalAdjusters. These include finding the "last day of the month" and "next Wednesday". Key date-time classes also implement the TemporalAdjuster interface, such as Month and MonthDay. The adjuster is responsible for handling special cases, such as the varying lengths of month and leap years.
For example this code returns a date on the last day of July: import static java.time.Month.*; import static java.time.temporal.TemporalAdjusters.*; result = localDate.with(JULY).with(lastDayOfMonth()); The result of this method is obtained by invoking the TemporalAdjuster.adjustInto(Temporal) method on the specified adjuster passing this as the argument.This instance is immutable and unaffected by this method call.
public LocalDate with(TemporalAdjuster adjuster) {
    // optimizations
    if (adjuster instanceof LocalDate) {
        return (LocalDate) adjuster;
    }
    return (LocalDate) adjuster.adjustInto(this);
}​

Specified by : with in interface ChronoLocalDateSpecified by:with in interface Temporal
Parameters : adjuster - the adjuster to use, not null
Returns : a LocalDate based on this with the adjustment made, not null
Throws : DateTimeException - if the adjustment cannot be made
             ArithmeticException - if numeric overflow occurs

여러 LocalDate의 필드 중 하나를 변경할 수 있는 with 메서드입니다.

이 메서드는 TemporalAdjuster이라는 인터페이스를 통해 변경을 하는 전략 패턴을 띄고 있습니다.

대표적인 구현체로는 'Month', 'Year', 'TomporalAdjusters'이 있습니다.

 

 

 

with(TemporalField field, long newValue)

public LocalDate with​(TemporalField field, long newValue)
Returns a copy of this date with the specified field set to a new value.This returns a LocalDate, based on this one, with the value for the specified field changed. This can be used to change any supported field, such as the year, month or day-of-month. If it is not possible to set the value, because the field is not supported or for some other reason, an exception is thrown.In some cases, changing the specified field can cause the resulting date to become invalid, such as changing the month from 31st January to February would make the day-of-month invalid. In cases like this, the field is responsible for resolving the date. Typically it will choose the previous valid date, which would be the last valid day of February in this example.If the field is a ChronoField then the adjustment is implemented here. The supported fields behave as follows:
In that case, the day-of-month is adjusted to the maximum valid value for the new month and year.ERA - Returns a LocalDate with the specified era. The year-of-era and month will be unchanged. The day-of-month will also be unchanged, unless it would be invalid for the new month and year. In that case, the day-of-month is adjusted to the maximum valid value for the new month and year.In all cases, if the new value is outside the valid range of values for the field then a DateTimeException will be thrown.All other ChronoField instances will throw an UnsupportedTemporalTypeException.If the field is not a ChronoField, then the result of this method is obtained by invoking TemporalField.adjustInto(Temporal, long) passing this as the argument. In this case, the field determines whether and how to adjust the instant.This instance is immutable and unaffected by this method call.
public LocalDate with(TemporalField field, long newValue) {
    if (field instanceof ChronoField) {
        ChronoField f = (ChronoField) field;
        f.checkValidValue(newValue);
        switch (f) {
            case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek().getValue());
            case ALIGNED_DAY_OF_WEEK_IN_MONTH: 
                return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
            case ALIGNED_DAY_OF_WEEK_IN_YEAR: 
                return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
            case DAY_OF_MONTH: return withDayOfMonth((int) newValue);
            case DAY_OF_YEAR: return withDayOfYear((int) newValue);
            case EPOCH_DAY: return LocalDate.ofEpochDay(newValue);
            case ALIGNED_WEEK_OF_MONTH: 
                return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH));
            case ALIGNED_WEEK_OF_YEAR: 
                return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR));
            case MONTH_OF_YEAR: return withMonth((int) newValue);
            case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());
            case YEAR_OF_ERA: return withYear((int) (year >= 1 ? newValue : 1 - newValue));
            case YEAR: return withYear((int) newValue);
            case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year));
        }
        throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
    }
    return field.adjustInto(this, newValue);
}​

Specified by : with in interface ChronoLocalDate
Specified by : with in interface Temporal
Parameters : field - the field to set in the result, not nullnewValue - the new value of the field in the result
Returns : a LocalDate based on this with the specified field set, not null
Throws : DateTimeException - if the field cannot be set
            UnsupportedTemporalTypeException - if the field is not supported
            ArithmeticException - if numeric overflow occurs

TemporalField로 수정할 필드를 정한 후 newValue를 통해 수정을 한 뒤 새로운 인스턴스를 반환합니다.

지원하지 않는 TemporalField (isSupported = false)인 경우 예외가 발생합니다.

 

TemporalField 설명
DAY_OF_WEEK 같은 주의 지정된 요일이 있는 LocalDate 반환
ALIGNED_DAY_OF_WEEK_IN_MONTH 지정된 요일이 월을 기준으로 정렬된 LocalDate 반환
ALIGNED_DAY_OF_WEEK_IN_YEAR 지정된 요일이 연도를 기준으로 정렬된 LocalDate 반환
DAY_OF_MONTH 같은 달의 제공받은 long일로 이동합니다.
DAY_OF_YEAR 같은 연도를 기준으로 제공받은 long일로 이동합니다 (범위 : 1 - 366일[윤년])
EPOCH_DAY 지정된 epoch_day로 부터 long일 만큼 지난 날짜를 반환합니다. (기준 : 1970.01.01)
ALIGNED_WEEK_OF_MONTH 해당 달의 long번째 주의 같은 요일인 날짜를 반환합니다.
ex : 2021-9-17 -> date.with(ALIGNED_WEEK_OF_MONTH, 1); = 2021-09-03
ALIGNED_WEEK_OF_YEAR 해당 연도에서 long번째 주의 같은 요일인 날짜를 반환합니다. (범위 : 1 - 52, 53주)
ex : 2021-9-17 -> date.with(ALIGNED_WEEK_OF_YEAR, 4); = 2021-01-22
MONTH_OF_YEAR 해당 날짜에서 long월로 이동한 LocalDate를 반환합니다.
ex : 2021-9-17 -> date.with(MONTH_OF_YEAR, 3); = 2021-03-17
PROLEPTIC_MONTH 0000년 1월 1일을 시작점으로 잡아 long월 후로 이동한 LocalDate를 반환합니다.
ex : 2021-9-17 -> date.with(PROLEPTIC_MONTH, 3); = 0000-04-17
YEAR_OF_ERA 0000년 1월 1일을 시작점으로 잡아 long년 후로 이동한 LocalDate를 반환합니다.
ex : 2021-9-17 -> date.with(YEAR_OF_ERA, 1010); = 1010-09-17
YEAR 해당 날짜에서 long년으로 이동한 LocalDate를 반환합니다.
ex : 2021-9-17 -> date.with(YEAR, 2020); = 2020-09-17
ERA 0이면 BCE, 1이면 CE로 잡아 LocalDate를 반환합니다.
ex : 2021-9-17 -> date.with(ERA, 0); = -2020-09-17
      2021-9-17 -> date.with(ERA, 1); = 2021-09-17

ALIGNED에 대한 자세한 정보는 번외에서 확인하시기 바랍니다!

 

◎ with...

메서드 설명
withYear 해당 int 연도로 변경된 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.withYear(1010); = 1010-09-17
withMonth 해당 int 월로 변경된 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.withMonth(11); = 2021-11-17
withDayOfMonth 같은 년 월에서 해당 int 일로 변경된 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.withDayOfMonth(10); = 2021-09-10
withDayOfYear 해당 int 일로 변경된 LocalDate 인스턴스를 반환합니다. (1 - 365)
ex : 2021-9-17 -> date.with(YEAR_OF_ERA, 330); = 2021-11-26

 

 

 

◎ plus

public LocalDate plus​(TemporalAmount amountToAdd)
Returns a copy of this date with the specified amount added.This returns a LocalDate, based on this one, with the specified amount added. The amount is typically Period but may be any other type implementing the TemporalAmount interface.The calculation is delegated to the amount object by calling TemporalAmount.addTo(Temporal). The amount implementation is free to implement the addition in any way it wishes, however it typically calls back to plus(long, TemporalUnit). Consult the documentation of the amount implementation to determine if it can be successfully added.This instance is immutable and unaffected by this method call.
public LocalDate plus(TemporalAmount amountToAdd) {
    if (amountToAdd instanceof Period) {
        Period periodToAdd = (Period) amountToAdd;
        return plusMonths(periodToAdd.toTotalMonths()).plusDays(periodToAdd.getDays());
    }
    Objects.requireNonNull(amountToAdd, "amountToAdd");
    return (LocalDate) amountToAdd.addTo(this);
}​

Specified by : plus in interface ChronoLocalDateSpecified by:plus in interface Temporal
Parameters : amountToAdd - the amount to add, not null
Returns : a LocalDate based on this date with the addition made, not null
Throws : DateTimeException - if the addition cannot be made
             ArithmeticException - if numeric overflow occurs

지정된 TemporalAmount 만큼 추가된 날짜의 복사본(새로운 인스턴스)을 반환합니다.

TemporalAmount는 기간(Month, Year)일 수도 TemporalAmount 구현체일 수도 있습니다.

대표적인 구현체로는 Duration, Period가 있습니다.

 

오버로드 메서드인 plus(long amountToAdd, TemporalUnit unit) 로 더욱 명시적으로 LocalDate 인스턴스를 반환할 수 있습니다.

    public LocalDate plus(long amountToAdd, TemporalUnit unit) {
        if (unit instanceof ChronoUnit) {
            ChronoUnit f = (ChronoUnit) unit;
            switch (f) {
                case DAYS: return plusDays(amountToAdd);
                case WEEKS: return plusWeeks(amountToAdd);
                case MONTHS: return plusMonths(amountToAdd);
                case YEARS: return plusYears(amountToAdd);
                case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
                case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
                case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
                case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
            }
            throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
        }
        return unit.addTo(this, amountToAdd);
    }

TemporalUnit의 구현체는 이늄 ChronoUnit입니다.

 

 

 

◎ plus...

메서드 설명
plusYears int 년 후의 날짜 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.plusYears(2); = 2023-09-17
plusMonths int 월 후의 날짜 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.plusMonths(2); = 2021-11-17
plusWeeks int 주 후의 날짜 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.plusWeeks(3); = 2021-10-08
plusDays int 일 후의 날짜 LocalDate 인스턴스를 반환합니다.
ex : 2021-9-17 -> date.plusDays(10); = 2021-09-27

 

 

 

◎ minus

minus는 plus와 메커니즘이 똑같기 때문에 생략하겠습니다.

 

 

 

◎ query

public <R> R query​(TemporalQuery<R> query)
Queries this date using the specified query. This queries this date using the specified query strategy object. The TemporalQuery object defines the logic to be used to obtain the result. Read the documentation of the query to understand what the result of this method will be. The result of this method is obtained by invoking the TemporalQuery.queryFrom(TemporalAccessor) method on the specified query passing this as the argument. Specified by: query in interface ChronoLocalDate Specified by: query in interface TemporalAccessor
public <R> R query(TemporalQuery<R> query) {
    if (query == TemporalQueries.localDate()) {
        return (R) this;
    }
    return ChronoLocalDate.super.query(query);
}​

Type Parameters : R - the type of the result
Parameters : query - the query to invoke, not null
Returns : the query result, null may be returned (defined by the query)
Throws : DateTimeException - if unable to query (defined by the query)
             ArithmeticException - if numeric overflow occurs (defined by the query)

함수형 인터페이스 TemporalQuery를 사용해서 날짜를 쿼리하는 메서드입니다.

'queryFrom​(TemporalAccessor temporal)' 을 이용해 객체를 쿼리합니다.

// ex) 2월이라면 참, 아니면 거짓
TemporalQuery<Boolean> query = t -> t.get(ChronoField.MONTH_OF_YEAR) == Month.FEBRUARY.getValue();

LocalDateTime localDateTime = LocalDateTime.now() //  2021-09-17:T20:00:00
localDateTime.query(query) // false

 

◎ adjustInto

public Temporal adjustInto​(Temporal temporal)
Adjusts the specified temporal object to have the same date as this object.
This returns a temporal object of the same observable type as the input with the date changed to be the same as this.The adjustment is equivalent to using Temporal.with(TemporalField, long) passing ChronoField.EPOCH_DAY as the field.In most cases, it is clearer to reverse the calling pattern by using Temporal.with(TemporalAdjuster): 
// these two lines are equivalent, but the second approach is recommended
temporal = thisLocalDate.adjustInto(temporal);
temporal = temporal.with(thisLocalDate);​

 

public Temporal adjustInto(Temporal temporal) {
    return ChronoLocalDate.super.adjustInto(temporal);
}

This instance is immutable and unaffected by this method call.
Specified by : adjustInto in interface ChronoLocalDateSpecified by:adjustInto in interface TemporalAdjuster
Parameters : temporal - the target object to be adjusted, not nullReturns:the adjusted object, not null
Throws : DateTimeException - if unable to make the adjustment
            ArithmeticException - if numeric overflow occurs

입력한 파라미터와 날짜가 같도록 LocalDate를 조절하는 메서드입니다.

작동 방식은 with과 똑같습니다. (with의 사용을 더욱 권장합니다.)

 

 

 

◎ until

public long until​(Temporal endExclusive, TemporalUnit unit)
Calculates the amount of time until another date in terms of the specified unit.
This calculates the amount of time between two LocalDate objects in terms of a single TemporalUnit. The start and end points are this and the specified date. The result will be negative if the end is before the start. The Temporal passed to this method is converted to a LocalDate using from(TemporalAccessor). For example, the amount in days between two dates can be calculated using startDate.until(endDate, DAYS).
The calculation returns a whole number, representing the number of complete units between the two dates. For example, the amount in months between 2012-06-15 and 2012-08-14 will only be one month as it is one day short of two months.
There are two equivalent ways of using this method. The first is to invoke this method.
The second is to use TemporalUnit.between(Temporal, Temporal): 
// these two lines are equivalent 
amount = start.until(end, MONTHS);
amount = MONTHS.between(start, end);​

The choice should be made based on which makes the code more readable.The calculation is implemented in this method for ChronoUnit. The units DAYS, WEEKS, MONTHS, YEARS, DECADES, CENTURIES, MILLENNIA and ERAS are supported. Other ChronoUnit values will throw an exception.If the unit is not a ChronoUnit, then the result of this method is obtained by invoking TemporalUnit.between(Temporal, Temporal) passing this as the first argument and the converted input temporal as the second argument.This instance is immutable and unaffected by this method call.
public long until(Temporal endExclusive, TemporalUnit unit) {
    LocalDate end = LocalDate.from(endExclusive);
    if (unit instanceof ChronoUnit) {
        switch ((ChronoUnit) unit) {
            case DAYS: return daysUntil(end);
            case WEEKS: return daysUntil(end) / 7;
            case MONTHS: return monthsUntil(end);
            case YEARS: return monthsUntil(end) / 12;
            case DECADES: return monthsUntil(end) / 120;
            case CENTURIES: return monthsUntil(end) / 1200;
            case MILLENNIA: return monthsUntil(end) / 12000;
            case ERAS: return end.getLong(ERA) - getLong(ERA);
        }
        throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
    }
    return unit.between(this, end);
}​

Specified by : until in interface ChronoLocalDate
Specified by : until in interface Temporal
Parameters : endExclusive - the end date, exclusive, which is converted to a LocalDate, not nullunit - the unit to measure the amount in, not null
Returns : the amount of time between this date and the end date
Throws :
DateTimeException - if the amount cannot be calculated, or the end temporal cannot be converted to a LocalDate
UnsupportedTemporalTypeException - if the unit is not supported
ArithmeticException - if numeric overflow occurs

두 날짜 사이의 차를 구하는 메서드로 각 ChronoUnit들의 between과 같은 기능을 하는 메서드입니다.

until과 between 메서드 둘 중 가독성이 좋은 것을 골라서 사용하시면 됩니다.

 

◎ datesUntil

public Stream<LocalDate> datesUntil​(LocalDate endExclusive)
Returns a sequential ordered stream of dates. The returned stream starts from this date (inclusive) and goes to endExclusive (exclusive) by an incremental step of 1 day.This method is equivalent to datesUntil(endExclusive, Period.ofDays(1)).
Parameters : endExclusive - the end date, exclusive, not null
Returns : a sequential Stream for the range of LocalDate values
Throws : IllegalArgumentException - if end date is before this dateSince:9

순차적으로 정렬된 날짜 스트림을 반환합니다.

이 메서드는 datesUntil(endExclusive, Period.ofDays(1))과 동일합니다.

 

◎ format

public String format​(DateTimeFormatter formatter)
Formats this date using the specified formatter.This date will be passed to the formatter to produce a string.
public String format(DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.format(this);
}​

Specified by : format in interface ChronoLocalDate
Parameters : formatter - the formatter to use, not null
Returns : the formatted date string, not null
Throws : DateTimeException - if an error occurs during printing

ISO_LOCAL_DATE상수를 통한 형식 부터, 커스텀된 형식의 문자열로 변환할 수 있는 파싱 메서드 입니다.

LocalDate date = LocalDate.of(2021, 9, 17);

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일");

String format1 = date.format(formatter1);	// 17/09/2021
String format2 = date.format(formatter2);	// 2021년 09월 17일

임의의 DateTImeFormatter을 이용해서 그 스타일로 적용된 String 문자열로 반환합니다!

 

 

 

◎ atTime

public LocalDateTime atTime​(LocalTime time)
Combines this date with a time to create a LocalDateTime.This returns a LocalDateTime formed from this date at the specified time. All possible combinations of date and time are valid.
public LocalDateTime atTime(LocalTime time) {
    return LocalDateTime.of(this, time);
}​

Specified by : atTime in interface ChronoLocalDate
Parameters : time - the time to combine with, not null
Returns : the local date-time formed from this date and the specified time, not null

빌드 형식으로 날짜 정보만 가지는 LocalDate에 시간 정보를 입력하는 메서드입니다.

// build 형식으로 날짜에 시간 추가
LocalDateTime dt1 = date.atTime(12, 10, 30);
LocalDateTime dt2 = date.atTime(time);

LocalTime을 여러 포맷으로 표현할 수 있는 만큼 atTime 역시 오버로드 여러 LocalTime 포맷으로 오버로딩 되어 있습니다.

 

◎ atStartOfDay

public LocalDateTime atStartOfDay( )
Combines this date with the time of midnight to create a LocalDateTime at the start of this date.This returns a LocalDateTime formed from this date at the time of midnight, 00:00, at the start of this date.
public LocalDateTime atStartOfDay() {
    return LocalDateTime.of(this, LocalTime.MIDNIGHT);
}​

Returns : the local date-time of midnight at the start of this date, not null

기존의 LocalDate에서 자정 00:00 시의 LocalTime 정보를 포함한 LocalDateTime을 반환합니다.

 

 

 

◎ atStartOfDay

public ZonedDateTime atStartOfDay​(ZoneId zone)
Returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone.Time-zone rules, such as daylight savings, mean that not every local date-time is valid for the specified zone, thus the local date-time may not be midnight.In most cases, there is only one valid offset for a local date-time. In the case of an overlap, there are two valid offsets, and the earlier one is used, corresponding to the first occurrence of midnight on the date. In the case of a gap, the zoned date-time will represent the instant just after the gap.If the zone ID is a ZoneOffset, then the result always has a time of midnight.To convert to a specific time in a given time-zone call atTime(LocalTime) followed by LocalDateTime.atZone(ZoneId).
public ZonedDateTime atStartOfDay(ZoneId zone) {
    Objects.requireNonNull(zone, "zone");
    // need to handle case where there is a gap from 11:30 to 00:30
    // standard ZDT factory would result in 01:00 rather than 00:30
    LocalDateTime ldt = atTime(LocalTime.MIDNIGHT);
    if (zone instanceof ZoneOffset == false) {
        ZoneRules rules = zone.getRules();
        ZoneOffsetTransition trans = rules.getTransition(ldt);
        if (trans != null && trans.isGap()) {
            ldt = trans.getDateTimeAfter();
        }
    }
    return ZonedDateTime.of(ldt, zone);
}​

Parameters : zone - the zone ID to use, not null
Returns : the zoned date-time formed from this date and the earliest valid time for the zone, not null

표준 시간대의 규칙에 의거해서 제공된 LocalDate로 부터 가장 빠른 ZonedDateTime을 반환합니다.

LocalDate date = LocalDate.of(2021, 9, 17);

ZoneId kst = ZoneId.of("Asia/Seoul");
ZoneId ect = ZoneId.of("Europe/Paris");
        
ZonedDateTime zonedDateTime1 = date.atStartOfDay(kst);	// 2021-09-17T00:00+09:00[Asia/Seoul]
ZonedDateTime zonedDateTime2 = date.atStartOfDay(ect);	// 2021-09-17T00:00+02:00[Europe/Paris]

그림 Zoneid

뒤의 +09:00은 이렇게 GMT 기준으로 더해지는 시간대를 의미합니다.

 

 

 

◎ toEpochSecond

public long toEpochSecond​(LocalTime time, ZoneOffset offset)
Converts this LocalDate to the number of seconds since the epoch of 1970-01-01T00:00:00Z.This combines this local date with the specified time and offset to calculate the epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. Instants on the time-line after the epoch are positive, earlier are negative.
    public long toEpochDay() {
        long y = year;
        long m = month;
        long total = 0;
        total += 365 * y;
        if (y >= 0) {
            total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
        } else {
            total -= y / -4 - y / -100 + y / -400;
        }
        total += ((367 * m - 362) / 12);
        total += day - 1;
        if (m > 2) {
            total--;
            if (isLeapYear() == false) {
                total--;
            }
        }
        return total - DAYS_0000_TO_1970;
    }​

Parameters : time - the local time, not nulloffset - the zone offset, not null
Returns : the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
Since : 9

파라미터 LocalDate를 시간과 오프셋을 결합해 Epoch의 기준(1970-01-01T00:00:00Z)를 기준으로 지난 시간을 초(second)의 단위로 환산해 반환합니다.

LocalDate date = LocalDate.of(2021, 9, 17);
LocalTime time = LocalTime.of(00, 00);

long l = date.toEpochSecond(time, ZoneOffset.MIN);	// 1631901600(s) -> 51년 9월 16일

 

 

◎ compareTo

public int compareTo​(ChronoLocalDate other)
Compares this date to another date.The comparison is primarily based on the date, from earliest to latest. It is "consistent with equals", as defined by Comparable.If all the dates being compared are instances of LocalDate, then the comparison will be entirely based on the date. If some dates being compared are in different chronologies, then the chronology is also considered, see ChronoLocalDate.compareTo(java.time.chrono.ChronoLocalDate).
Specified by:compareTo in interface ChronoLocalDateSpecified by:compareTo in interface Comparable<ChronoLocalDate>
Parameters : other - the other date to compare to, not null
Returns : the comparator value, negative if less, positive if greater

date1.compareTo(date2)라면, date1에서 date2를 뺀 날짜입니다.

LocalDate date1 = LocalDate.of(2021, 9, 17);
LocalDate date2 = LocalDate.of(2021, 9, 20);

int i = date1.compareTo(date2);	// -3
int j = date2.compareTo(date1);	// 3

between과 같은 기능을 합니다.

 

 

5. 데이터 판별

◎ is...

isSupported와 같이 무언가를 판별하는 메서드 입니다.

메서드 설명
isAfter 이 날짜가 지정된 날짜 이후인지를 판별 후 boolean 반환
LocalDate date1 = LocalDate.of(2021, 9, 17);
LocalDate date2 = LocalDate.of(2021, 9, 20);

date1.isAfter(date2) // false
date2.isAfter(date1) // true
isBefore 이 날짜가 지정된 날짜 이전인지를 판별 후 boolean 반환
LocalDate date1 = LocalDate.of(2021, 9, 17);
LocalDate date2 = LocalDate.of(2021, 9, 20);

date1.isBefore(date2) // true
date2.isBefore(date1) // false
isEqual 이 날짜가 지정된 날짜와 같은지를 판별 후 boolean 반환
LocalDate date1 = LocalDate.of(2021, 9, 17);
LocalDate date2 = LocalDate.of(2021, 9, 20);
LocalDate date3 = LocalDate.of(2021, 9, 17);

date1.isEqual(date2) // false
date1.isBefore(date3) // true

 

◎ isSupported

public boolean isSupported​(TemporalField field)
Checks if the specified field is supported. This checks if this date can be queried for the specified field. If false, then calling the range, get and with(TemporalField, long) methods will throw an exception.If the field is a ChronoField then the query is implemented here.
The supported fields are :
DAY_OF_WEEK / ALIGNED_DAY_OF_WEEK_IN_MONTH ALIGNED_DAY_OF_WEEK_IN_YEAR DAY_OF_MONTH
DAY_OF_YEAR / EPOCH_DAY / ALIGNED_WEEK_OF_MONTH / ALIGNED_WEEK_OF_YEAR / MONTH_OF_YEAR PROLEPTIC_MONTH / YEAR_OF_ERA / YEAR, ERA
All other ChronoField instances will return false.If the field is not a ChronoField, then the result of this method is obtained by invoking TemporalField.isSupportedBy(TemporalAccessor) passing this as the argument. Whether the field is supported is determined by the field.
Specified by : isSupported in interface ChronoLocalDate
Specified by:  isSupported in interface TemporalAccessor
public boolean isSupported(TemporalField field) {
    return ChronoLocalDate.super.isSupported(field);
}​

Parameters : field - the field to check, null returns false
Returns : true if the field is supported on this date, false if not

차후 추가적인 가공을 위해서는 지원 가능한 범위를 파악해야 합니다. 이를 위해서 파라미터로 제시된 필드가 지원되는지 확인하는 메서드입니다. false인 경우 range, get, with(TemporalField, long) 메서드 호출 시 예외가 발생합니다.

위 필드(LocalDate가 지원하는 필드)를 제외한 다른 ChronoField 인스턴스는 모두 false를 반환합니다.

 

추가적으로 TemporalUnit를 검증하는 메서드가 오버로딩 되어 있습니다.

(TemporalUnit -> DAY, WEEKS, MONTHS, UEARS, DECADES, CENTURIES, MILLENNIA, ERAS)

// LocalTime과 LocalDate가 지원하는 필드는 각각 다르다!
LocalDate date = LocalDate.of(2021, 9, 17);
LocalTime time = LocalTime.of(11, 30);


boolean supported1 = date.isSupported(ChronoField.DAY_OF_YEAR);	// true
boolean supported2 = date.isSupported(ChronoField.AMPM_OF_DAY);	// false

boolean supported2 = time.isSupported(ChronoField.AMPM_OF_DAY);	// true
boolean supported3 = time.isSupported(ChronoField.DAY_OF_MONTH);	// false

이렇게 날짜 관련 필드들은 LocalDate가 지원하는 한편, 시간 관련필드는 지원하지 않는 것을 알 수 있고,

LocalTime은 그 반대의 경우에만 지원하는 것을 알 수 있습니다!

 

 

 

번외

ALIGNED_DAY_OF_WEEK_IN_MONTH

월의 경우 각 월에서 1일의 요일의 값을 1로 매핑합니다.

그림. ALIGNED_DAY_OF_WEEK_IN_MONTH

9월의 경우 1일이 수요일이기 때문에 1 = '수' / 2 = '목' / 3 = '금' /... 이런 식으로 매핑됩니다.

 

 

 

ALIGNED_DAY_OF_WEEK_IN_YEAR

연도 중 1월 1일의 요일의 값을 1로 매핑합니다.

그림. ALIGNED_DAY_OF_WEEK_IN_YEAR

2021년 1월 1일은 금요일이기 때문에  1 = '금' / 2 = '토' / 3 = '일' / ... 식으로 매핑됩니다.

 

 

 

ALIGNED_WEEK_OF_MONTH

해당 달에서 주를 기준으로 값을 매핑합니다.

그림. ALIGNED_WEEK_OF_MONTH

만약 기준이 22일이라면

1 -> 1일 / 2 -> 9일 / 3 -> 15일 / 4 -> 22일 / 5 -> 29일이 됩니다.

 

 

 

ALIGNED_WEEK_OF_YEAR

해당 연도에서 주를 기준으로 값을 매핑합니다.

1월 첫 번째 주를 1로 매핑해서 최대 52, 53까지 매핑이 가능합니다.

 

출처

LocalDate (Java SE 10 & JDK 10 ) (oracle.com)

 

LocalDate (Java SE 10 & JDK 10 )

Returns a sequential ordered stream of dates by given incremental step. The returned stream starts from this date (inclusive) and goes to endExclusive (exclusive). The n-th date which appears in the stream is equal to this.plus(step.multipliedBy(n)) (but t

docs.oracle.com

 

'JAVA > Reference' 카테고리의 다른 글

Optional  (0) 2021.09.16
Spliterator 인터페이스  (0) 2021.08.23