Path: blob/master/src/java.base/share/classes/java/time/LocalDateTime.java
41152 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.LocalTime.HOURS_PER_DAY;64import static java.time.LocalTime.MICROS_PER_DAY;65import static java.time.LocalTime.MILLIS_PER_DAY;66import static java.time.LocalTime.MINUTES_PER_DAY;67import static java.time.LocalTime.NANOS_PER_DAY;68import static java.time.LocalTime.NANOS_PER_HOUR;69import static java.time.LocalTime.NANOS_PER_MINUTE;70import static java.time.LocalTime.NANOS_PER_SECOND;71import static java.time.LocalTime.SECONDS_PER_DAY;72import static java.time.temporal.ChronoField.NANO_OF_SECOND;7374import java.io.DataInput;75import java.io.DataOutput;76import java.io.IOException;77import java.io.InvalidObjectException;78import java.io.ObjectInputStream;79import java.io.Serializable;80import java.time.chrono.ChronoLocalDateTime;81import java.time.format.DateTimeFormatter;82import java.time.format.DateTimeParseException;83import java.time.temporal.ChronoField;84import java.time.temporal.ChronoUnit;85import java.time.temporal.Temporal;86import java.time.temporal.TemporalAccessor;87import java.time.temporal.TemporalAdjuster;88import java.time.temporal.TemporalAmount;89import java.time.temporal.TemporalField;90import java.time.temporal.TemporalQueries;91import java.time.temporal.TemporalQuery;92import java.time.temporal.TemporalUnit;93import java.time.temporal.UnsupportedTemporalTypeException;94import java.time.temporal.ValueRange;95import java.time.zone.ZoneRules;96import java.util.Objects;9798/**99* A date-time without a time-zone in the ISO-8601 calendar system,100* such as {@code 2007-12-03T10:15:30}.101* <p>102* {@code LocalDateTime} is an immutable date-time object that represents a date-time,103* often viewed as year-month-day-hour-minute-second. Other date and time fields,104* such as day-of-year, day-of-week and week-of-year, can also be accessed.105* Time is represented to nanosecond precision.106* For example, the value "2nd October 2007 at 13:45.30.123456789" can be107* stored in a {@code LocalDateTime}.108* <p>109* This class does not store or represent a time-zone.110* Instead, it is a description of the date, as used for birthdays, combined with111* the local time as seen on a wall clock.112* It cannot represent an instant on the time-line without additional information113* such as an offset or time-zone.114* <p>115* The ISO-8601 calendar system is the modern civil calendar system used today116* in most of the world. It is equivalent to the proleptic Gregorian calendar117* system, in which today's rules for leap years are applied for all time.118* For most applications written today, the ISO-8601 rules are entirely suitable.119* However, any application that makes use of historical dates, and requires them120* to be accurate will find the ISO-8601 approach unsuitable.121* <p>122* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>123* class; programmers should treat instances that are124* {@linkplain #equals(Object) equal} as interchangeable and should not125* use instances for synchronization, or unpredictable behavior may126* occur. For example, in a future release, synchronization may fail.127* The {@code equals} method should be used for comparisons.128*129* @implSpec130* This class is immutable and thread-safe.131*132* @since 1.8133*/134@jdk.internal.ValueBased135public final class LocalDateTime136implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {137138/**139* The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'.140* This is the local date-time of midnight at the start of the minimum date.141* This combines {@link LocalDate#MIN} and {@link LocalTime#MIN}.142* This could be used by an application as a "far past" date-time.143*/144public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN);145/**146* The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'.147* This is the local date-time just before midnight at the end of the maximum date.148* This combines {@link LocalDate#MAX} and {@link LocalTime#MAX}.149* This could be used by an application as a "far future" date-time.150*/151public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX);152153/**154* Serialization version.155*/156@java.io.Serial157private static final long serialVersionUID = 6207766400415563566L;158159/**160* The date part.161*/162private final LocalDate date;163/**164* The time part.165*/166private final LocalTime time;167168//-----------------------------------------------------------------------169/**170* Obtains the current date-time from the system clock in the default time-zone.171* <p>172* This will query the {@link Clock#systemDefaultZone() system clock} in the default173* time-zone to obtain the current date-time.174* <p>175* Using this method will prevent the ability to use an alternate clock for testing176* because the clock is hard-coded.177*178* @return the current date-time using the system clock and default time-zone, not null179*/180public static LocalDateTime now() {181return now(Clock.systemDefaultZone());182}183184/**185* Obtains the current date-time from the system clock in the specified time-zone.186* <p>187* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.188* Specifying the time-zone avoids dependence on the default time-zone.189* <p>190* Using this method will prevent the ability to use an alternate clock for testing191* because the clock is hard-coded.192*193* @param zone the zone ID to use, not null194* @return the current date-time using the system clock, not null195*/196public static LocalDateTime now(ZoneId zone) {197return now(Clock.system(zone));198}199200/**201* Obtains the current date-time from the specified clock.202* <p>203* This will query the specified clock to obtain the current date-time.204* Using this method allows the use of an alternate clock for testing.205* The alternate clock may be introduced using {@link Clock dependency injection}.206*207* @param clock the clock to use, not null208* @return the current date-time, not null209*/210public static LocalDateTime now(Clock clock) {211Objects.requireNonNull(clock, "clock");212final Instant now = clock.instant(); // called once213ZoneOffset offset = clock.getZone().getRules().getOffset(now);214return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);215}216217//-----------------------------------------------------------------------218/**219* Obtains an instance of {@code LocalDateTime} from year, month,220* day, hour and minute, setting the second and nanosecond to zero.221* <p>222* This returns a {@code LocalDateTime} with the specified year, month,223* day-of-month, hour and minute.224* The day must be valid for the year and month, otherwise an exception will be thrown.225* The second and nanosecond fields will be set to zero.226*227* @param year the year to represent, from MIN_YEAR to MAX_YEAR228* @param month the month-of-year to represent, not null229* @param dayOfMonth the day-of-month to represent, from 1 to 31230* @param hour the hour-of-day to represent, from 0 to 23231* @param minute the minute-of-hour to represent, from 0 to 59232* @return the local date-time, not null233* @throws DateTimeException if the value of any field is out of range,234* or if the day-of-month is invalid for the month-year235*/236public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {237LocalDate date = LocalDate.of(year, month, dayOfMonth);238LocalTime time = LocalTime.of(hour, minute);239return new LocalDateTime(date, time);240}241242/**243* Obtains an instance of {@code LocalDateTime} from year, month,244* day, hour, minute and second, setting the nanosecond to zero.245* <p>246* This returns a {@code LocalDateTime} with the specified year, month,247* day-of-month, hour, minute and second.248* The day must be valid for the year and month, otherwise an exception will be thrown.249* The nanosecond field will be set to zero.250*251* @param year the year to represent, from MIN_YEAR to MAX_YEAR252* @param month the month-of-year to represent, not null253* @param dayOfMonth the day-of-month to represent, from 1 to 31254* @param hour the hour-of-day to represent, from 0 to 23255* @param minute the minute-of-hour to represent, from 0 to 59256* @param second the second-of-minute to represent, from 0 to 59257* @return the local date-time, not null258* @throws DateTimeException if the value of any field is out of range,259* or if the day-of-month is invalid for the month-year260*/261public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) {262LocalDate date = LocalDate.of(year, month, dayOfMonth);263LocalTime time = LocalTime.of(hour, minute, second);264return new LocalDateTime(date, time);265}266267/**268* Obtains an instance of {@code LocalDateTime} from year, month,269* day, hour, minute, second and nanosecond.270* <p>271* This returns a {@code LocalDateTime} with the specified year, month,272* day-of-month, hour, minute, second and nanosecond.273* The day must be valid for the year and month, otherwise an exception will be thrown.274*275* @param year the year to represent, from MIN_YEAR to MAX_YEAR276* @param month the month-of-year to represent, not null277* @param dayOfMonth the day-of-month to represent, from 1 to 31278* @param hour the hour-of-day to represent, from 0 to 23279* @param minute the minute-of-hour to represent, from 0 to 59280* @param second the second-of-minute to represent, from 0 to 59281* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999282* @return the local date-time, not null283* @throws DateTimeException if the value of any field is out of range,284* or if the day-of-month is invalid for the month-year285*/286public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {287LocalDate date = LocalDate.of(year, month, dayOfMonth);288LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);289return new LocalDateTime(date, time);290}291292//-----------------------------------------------------------------------293/**294* Obtains an instance of {@code LocalDateTime} from year, month,295* day, hour and minute, setting the second and nanosecond to zero.296* <p>297* This returns a {@code LocalDateTime} with the specified year, month,298* day-of-month, hour and minute.299* The day must be valid for the year and month, otherwise an exception will be thrown.300* The second and nanosecond fields will be set to zero.301*302* @param year the year to represent, from MIN_YEAR to MAX_YEAR303* @param month the month-of-year to represent, from 1 (January) to 12 (December)304* @param dayOfMonth the day-of-month to represent, from 1 to 31305* @param hour the hour-of-day to represent, from 0 to 23306* @param minute the minute-of-hour to represent, from 0 to 59307* @return the local date-time, not null308* @throws DateTimeException if the value of any field is out of range,309* or if the day-of-month is invalid for the month-year310*/311public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) {312LocalDate date = LocalDate.of(year, month, dayOfMonth);313LocalTime time = LocalTime.of(hour, minute);314return new LocalDateTime(date, time);315}316317/**318* Obtains an instance of {@code LocalDateTime} from year, month,319* day, hour, minute and second, setting the nanosecond to zero.320* <p>321* This returns a {@code LocalDateTime} with the specified year, month,322* day-of-month, hour, minute and second.323* The day must be valid for the year and month, otherwise an exception will be thrown.324* The nanosecond field will be set to zero.325*326* @param year the year to represent, from MIN_YEAR to MAX_YEAR327* @param month the month-of-year to represent, from 1 (January) to 12 (December)328* @param dayOfMonth the day-of-month to represent, from 1 to 31329* @param hour the hour-of-day to represent, from 0 to 23330* @param minute the minute-of-hour to represent, from 0 to 59331* @param second the second-of-minute to represent, from 0 to 59332* @return the local date-time, not null333* @throws DateTimeException if the value of any field is out of range,334* or if the day-of-month is invalid for the month-year335*/336public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) {337LocalDate date = LocalDate.of(year, month, dayOfMonth);338LocalTime time = LocalTime.of(hour, minute, second);339return new LocalDateTime(date, time);340}341342/**343* Obtains an instance of {@code LocalDateTime} from year, month,344* day, hour, minute, second and nanosecond.345* <p>346* This returns a {@code LocalDateTime} with the specified year, month,347* day-of-month, hour, minute, second and nanosecond.348* The day must be valid for the year and month, otherwise an exception will be thrown.349*350* @param year the year to represent, from MIN_YEAR to MAX_YEAR351* @param month the month-of-year to represent, from 1 (January) to 12 (December)352* @param dayOfMonth the day-of-month to represent, from 1 to 31353* @param hour the hour-of-day to represent, from 0 to 23354* @param minute the minute-of-hour to represent, from 0 to 59355* @param second the second-of-minute to represent, from 0 to 59356* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999357* @return the local date-time, not null358* @throws DateTimeException if the value of any field is out of range,359* or if the day-of-month is invalid for the month-year360*/361public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {362LocalDate date = LocalDate.of(year, month, dayOfMonth);363LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);364return new LocalDateTime(date, time);365}366367/**368* Obtains an instance of {@code LocalDateTime} from a date and time.369*370* @param date the local date, not null371* @param time the local time, not null372* @return the local date-time, not null373*/374public static LocalDateTime of(LocalDate date, LocalTime time) {375Objects.requireNonNull(date, "date");376Objects.requireNonNull(time, "time");377return new LocalDateTime(date, time);378}379380//-------------------------------------------------------------------------381/**382* Obtains an instance of {@code LocalDateTime} from an {@code Instant} and zone ID.383* <p>384* This creates a local date-time based on the specified instant.385* First, the offset from UTC/Greenwich is obtained using the zone ID and instant,386* which is simple as there is only one valid offset for each instant.387* Then, the instant and offset are used to calculate the local date-time.388*389* @param instant the instant to create the date-time from, not null390* @param zone the time-zone, which may be an offset, not null391* @return the local date-time, not null392* @throws DateTimeException if the result exceeds the supported range393*/394public static LocalDateTime ofInstant(Instant instant, ZoneId zone) {395Objects.requireNonNull(instant, "instant");396Objects.requireNonNull(zone, "zone");397ZoneRules rules = zone.getRules();398ZoneOffset offset = rules.getOffset(instant);399return ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);400}401402/**403* Obtains an instance of {@code LocalDateTime} using seconds from the404* epoch of 1970-01-01T00:00:00Z.405* <p>406* This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field407* to be converted to a local date-time. This is primarily intended for408* low-level conversions rather than general application usage.409*410* @param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z411* @param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999412* @param offset the zone offset, not null413* @return the local date-time, not null414* @throws DateTimeException if the result exceeds the supported range,415* or if the nano-of-second is invalid416*/417public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {418Objects.requireNonNull(offset, "offset");419NANO_OF_SECOND.checkValidValue(nanoOfSecond);420long localSecond = epochSecond + offset.getTotalSeconds(); // overflow caught later421long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);422int secsOfDay = Math.floorMod(localSecond, SECONDS_PER_DAY);423LocalDate date = LocalDate.ofEpochDay(localEpochDay);424LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + nanoOfSecond);425return new LocalDateTime(date, time);426}427428//-----------------------------------------------------------------------429/**430* Obtains an instance of {@code LocalDateTime} from a temporal object.431* <p>432* This obtains a local date-time based on the specified temporal.433* A {@code TemporalAccessor} represents an arbitrary set of date and time information,434* which this factory converts to an instance of {@code LocalDateTime}.435* <p>436* The conversion extracts and combines the {@code LocalDate} and the437* {@code LocalTime} from the temporal object.438* Implementations are permitted to perform optimizations such as accessing439* those fields that are equivalent to the relevant objects.440* <p>441* This method matches the signature of the functional interface {@link TemporalQuery}442* allowing it to be used as a query via method reference, {@code LocalDateTime::from}.443*444* @param temporal the temporal object to convert, not null445* @return the local date-time, not null446* @throws DateTimeException if unable to convert to a {@code LocalDateTime}447*/448public static LocalDateTime from(TemporalAccessor temporal) {449if (temporal instanceof LocalDateTime) {450return (LocalDateTime) temporal;451} else if (temporal instanceof ZonedDateTime) {452return ((ZonedDateTime) temporal).toLocalDateTime();453} else if (temporal instanceof OffsetDateTime) {454return ((OffsetDateTime) temporal).toLocalDateTime();455}456try {457LocalDate date = LocalDate.from(temporal);458LocalTime time = LocalTime.from(temporal);459return new LocalDateTime(date, time);460} catch (DateTimeException ex) {461throw new DateTimeException("Unable to obtain LocalDateTime from TemporalAccessor: " +462temporal + " of type " + temporal.getClass().getName(), ex);463}464}465466//-----------------------------------------------------------------------467/**468* Obtains an instance of {@code LocalDateTime} from a text string such as {@code 2007-12-03T10:15:30}.469* <p>470* The string must represent a valid date-time and is parsed using471* {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE_TIME}.472*473* @param text the text to parse such as "2007-12-03T10:15:30", not null474* @return the parsed local date-time, not null475* @throws DateTimeParseException if the text cannot be parsed476*/477public static LocalDateTime parse(CharSequence text) {478return parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME);479}480481/**482* Obtains an instance of {@code LocalDateTime} from a text string using a specific formatter.483* <p>484* The text is parsed using the formatter, returning a date-time.485*486* @param text the text to parse, not null487* @param formatter the formatter to use, not null488* @return the parsed local date-time, not null489* @throws DateTimeParseException if the text cannot be parsed490*/491public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {492Objects.requireNonNull(formatter, "formatter");493return formatter.parse(text, LocalDateTime::from);494}495496//-----------------------------------------------------------------------497/**498* Constructor.499*500* @param date the date part of the date-time, validated not null501* @param time the time part of the date-time, validated not null502*/503private LocalDateTime(LocalDate date, LocalTime time) {504this.date = date;505this.time = time;506}507508/**509* Returns a copy of this date-time with the new date and time, checking510* to see if a new object is in fact required.511*512* @param newDate the date of the new date-time, not null513* @param newTime the time of the new date-time, not null514* @return the date-time, not null515*/516private LocalDateTime with(LocalDate newDate, LocalTime newTime) {517if (date == newDate && time == newTime) {518return this;519}520return new LocalDateTime(newDate, newTime);521}522523//-----------------------------------------------------------------------524/**525* Checks if the specified field is supported.526* <p>527* This checks if this date-time can be queried for the specified field.528* If false, then calling the {@link #range(TemporalField) range},529* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}530* methods will throw an exception.531* <p>532* If the field is a {@link ChronoField} then the query is implemented here.533* The supported fields are:534* <ul>535* <li>{@code NANO_OF_SECOND}536* <li>{@code NANO_OF_DAY}537* <li>{@code MICRO_OF_SECOND}538* <li>{@code MICRO_OF_DAY}539* <li>{@code MILLI_OF_SECOND}540* <li>{@code MILLI_OF_DAY}541* <li>{@code SECOND_OF_MINUTE}542* <li>{@code SECOND_OF_DAY}543* <li>{@code MINUTE_OF_HOUR}544* <li>{@code MINUTE_OF_DAY}545* <li>{@code HOUR_OF_AMPM}546* <li>{@code CLOCK_HOUR_OF_AMPM}547* <li>{@code HOUR_OF_DAY}548* <li>{@code CLOCK_HOUR_OF_DAY}549* <li>{@code AMPM_OF_DAY}550* <li>{@code DAY_OF_WEEK}551* <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}552* <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}553* <li>{@code DAY_OF_MONTH}554* <li>{@code DAY_OF_YEAR}555* <li>{@code EPOCH_DAY}556* <li>{@code ALIGNED_WEEK_OF_MONTH}557* <li>{@code ALIGNED_WEEK_OF_YEAR}558* <li>{@code MONTH_OF_YEAR}559* <li>{@code PROLEPTIC_MONTH}560* <li>{@code YEAR_OF_ERA}561* <li>{@code YEAR}562* <li>{@code ERA}563* </ul>564* All other {@code ChronoField} instances will return false.565* <p>566* If the field is not a {@code ChronoField}, then the result of this method567* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}568* passing {@code this} as the argument.569* Whether the field is supported is determined by the field.570*571* @param field the field to check, null returns false572* @return true if the field is supported on this date-time, false if not573*/574@Override575public boolean isSupported(TemporalField field) {576if (field instanceof ChronoField chronoField) {577return chronoField.isDateBased() || chronoField.isTimeBased();578}579return field != null && field.isSupportedBy(this);580}581582/**583* Checks if the specified unit is supported.584* <p>585* This checks if the specified unit can be added to, or subtracted from, this date-time.586* If false, then calling the {@link #plus(long, TemporalUnit)} and587* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.588* <p>589* If the unit is a {@link ChronoUnit} then the query is implemented here.590* The supported units are:591* <ul>592* <li>{@code NANOS}593* <li>{@code MICROS}594* <li>{@code MILLIS}595* <li>{@code SECONDS}596* <li>{@code MINUTES}597* <li>{@code HOURS}598* <li>{@code HALF_DAYS}599* <li>{@code DAYS}600* <li>{@code WEEKS}601* <li>{@code MONTHS}602* <li>{@code YEARS}603* <li>{@code DECADES}604* <li>{@code CENTURIES}605* <li>{@code MILLENNIA}606* <li>{@code ERAS}607* </ul>608* All other {@code ChronoUnit} instances will return false.609* <p>610* If the unit is not a {@code ChronoUnit}, then the result of this method611* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}612* passing {@code this} as the argument.613* Whether the unit is supported is determined by the unit.614*615* @param unit the unit to check, null returns false616* @return true if the unit can be added/subtracted, false if not617*/618@Override // override for Javadoc619public boolean isSupported(TemporalUnit unit) {620return ChronoLocalDateTime.super.isSupported(unit);621}622623//-----------------------------------------------------------------------624/**625* Gets the range of valid values for the specified field.626* <p>627* The range object expresses the minimum and maximum valid values for a field.628* This date-time is used to enhance the accuracy of the returned range.629* If it is not possible to return the range, because the field is not supported630* or for some other reason, an exception is thrown.631* <p>632* If the field is a {@link ChronoField} then the query is implemented here.633* The {@link #isSupported(TemporalField) supported fields} will return634* appropriate range instances.635* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.636* <p>637* If the field is not a {@code ChronoField}, then the result of this method638* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}639* passing {@code this} as the argument.640* Whether the range can be obtained is determined by the field.641*642* @param field the field to query the range for, not null643* @return the range of valid values for the field, not null644* @throws DateTimeException if the range for the field cannot be obtained645* @throws UnsupportedTemporalTypeException if the field is not supported646*/647@Override648public ValueRange range(TemporalField field) {649if (field instanceof ChronoField chronoField) {650return (chronoField.isTimeBased() ? time.range(field) : date.range(field));651}652return field.rangeRefinedBy(this);653}654655/**656* Gets the value of the specified field from this date-time as an {@code int}.657* <p>658* This queries this date-time for the value of the specified field.659* The returned value will always be within the valid range of values for the field.660* If it is not possible to return the value, because the field is not supported661* or for some other reason, an exception is thrown.662* <p>663* If the field is a {@link ChronoField} then the query is implemented here.664* The {@link #isSupported(TemporalField) supported fields} will return valid665* values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},666* {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH} which are too large to fit in667* an {@code int} and throw an {@code UnsupportedTemporalTypeException}.668* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.669* <p>670* If the field is not a {@code ChronoField}, then the result of this method671* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}672* passing {@code this} as the argument. Whether the value can be obtained,673* and what the value represents, is determined by the field.674*675* @param field the field to get, not null676* @return the value for the field677* @throws DateTimeException if a value for the field cannot be obtained or678* the value is outside the range of valid values for the field679* @throws UnsupportedTemporalTypeException if the field is not supported or680* the range of values exceeds an {@code int}681* @throws ArithmeticException if numeric overflow occurs682*/683@Override684public int get(TemporalField field) {685if (field instanceof ChronoField chronoField) {686return (chronoField.isTimeBased() ? time.get(field) : date.get(field));687}688return ChronoLocalDateTime.super.get(field);689}690691/**692* Gets the value of the specified field from this date-time as a {@code long}.693* <p>694* This queries this date-time for the value of the specified field.695* If it is not possible to return the value, because the field is not supported696* or for some other reason, an exception is thrown.697* <p>698* If the field is a {@link ChronoField} then the query is implemented here.699* The {@link #isSupported(TemporalField) supported fields} will return valid700* values based on this date-time.701* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.702* <p>703* If the field is not a {@code ChronoField}, then the result of this method704* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}705* passing {@code this} as the argument. Whether the value can be obtained,706* and what the value represents, is determined by the field.707*708* @param field the field to get, not null709* @return the value for the field710* @throws DateTimeException if a value for the field cannot be obtained711* @throws UnsupportedTemporalTypeException if the field is not supported712* @throws ArithmeticException if numeric overflow occurs713*/714@Override715public long getLong(TemporalField field) {716if (field instanceof ChronoField chronoField) {717return (chronoField.isTimeBased() ? time.getLong(field) : date.getLong(field));718}719return field.getFrom(this);720}721722//-----------------------------------------------------------------------723/**724* Gets the {@code LocalDate} part of this date-time.725* <p>726* This returns a {@code LocalDate} with the same year, month and day727* as this date-time.728*729* @return the date part of this date-time, not null730*/731@Override732public LocalDate toLocalDate() {733return date;734}735736/**737* Gets the year field.738* <p>739* This method returns the primitive {@code int} value for the year.740* <p>741* The year returned by this method is proleptic as per {@code get(YEAR)}.742* To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.743*744* @return the year, from MIN_YEAR to MAX_YEAR745*/746public int getYear() {747return date.getYear();748}749750/**751* Gets the month-of-year field from 1 to 12.752* <p>753* This method returns the month as an {@code int} from 1 to 12.754* Application code is frequently clearer if the enum {@link Month}755* is used by calling {@link #getMonth()}.756*757* @return the month-of-year, from 1 to 12758* @see #getMonth()759*/760public int getMonthValue() {761return date.getMonthValue();762}763764/**765* Gets the month-of-year field using the {@code Month} enum.766* <p>767* This method returns the enum {@link Month} for the month.768* This avoids confusion as to what {@code int} values mean.769* If you need access to the primitive {@code int} value then the enum770* provides the {@link Month#getValue() int value}.771*772* @return the month-of-year, not null773* @see #getMonthValue()774*/775public Month getMonth() {776return date.getMonth();777}778779/**780* Gets the day-of-month field.781* <p>782* This method returns the primitive {@code int} value for the day-of-month.783*784* @return the day-of-month, from 1 to 31785*/786public int getDayOfMonth() {787return date.getDayOfMonth();788}789790/**791* Gets the day-of-year field.792* <p>793* This method returns the primitive {@code int} value for the day-of-year.794*795* @return the day-of-year, from 1 to 365, or 366 in a leap year796*/797public int getDayOfYear() {798return date.getDayOfYear();799}800801/**802* Gets the day-of-week field, which is an enum {@code DayOfWeek}.803* <p>804* This method returns the enum {@link DayOfWeek} for the day-of-week.805* This avoids confusion as to what {@code int} values mean.806* If you need access to the primitive {@code int} value then the enum807* provides the {@link DayOfWeek#getValue() int value}.808* <p>809* Additional information can be obtained from the {@code DayOfWeek}.810* This includes textual names of the values.811*812* @return the day-of-week, not null813*/814public DayOfWeek getDayOfWeek() {815return date.getDayOfWeek();816}817818//-----------------------------------------------------------------------819/**820* Gets the {@code LocalTime} part of this date-time.821* <p>822* This returns a {@code LocalTime} with the same hour, minute, second and823* nanosecond as this date-time.824*825* @return the time part of this date-time, not null826*/827@Override828public LocalTime toLocalTime() {829return time;830}831832/**833* Gets the hour-of-day field.834*835* @return the hour-of-day, from 0 to 23836*/837public int getHour() {838return time.getHour();839}840841/**842* Gets the minute-of-hour field.843*844* @return the minute-of-hour, from 0 to 59845*/846public int getMinute() {847return time.getMinute();848}849850/**851* Gets the second-of-minute field.852*853* @return the second-of-minute, from 0 to 59854*/855public int getSecond() {856return time.getSecond();857}858859/**860* Gets the nano-of-second field.861*862* @return the nano-of-second, from 0 to 999,999,999863*/864public int getNano() {865return time.getNano();866}867868//-----------------------------------------------------------------------869/**870* Returns an adjusted copy of this date-time.871* <p>872* This returns a {@code LocalDateTime}, based on this one, with the date-time adjusted.873* The adjustment takes place using the specified adjuster strategy object.874* Read the documentation of the adjuster to understand what adjustment will be made.875* <p>876* A simple adjuster might simply set the one of the fields, such as the year field.877* A more complex adjuster might set the date to the last day of the month.878* <p>879* A selection of common adjustments is provided in880* {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.881* These include finding the "last day of the month" and "next Wednesday".882* Key date-time classes also implement the {@code TemporalAdjuster} interface,883* such as {@link Month} and {@link java.time.MonthDay MonthDay}.884* The adjuster is responsible for handling special cases, such as the varying885* lengths of month and leap years.886* <p>887* For example this code returns a date on the last day of July:888* <pre>889* import static java.time.Month.*;890* import static java.time.temporal.TemporalAdjusters.*;891*892* result = localDateTime.with(JULY).with(lastDayOfMonth());893* </pre>894* <p>895* The classes {@link LocalDate} and {@link LocalTime} implement {@code TemporalAdjuster},896* thus this method can be used to change the date, time or offset:897* <pre>898* result = localDateTime.with(date);899* result = localDateTime.with(time);900* </pre>901* <p>902* The result of this method is obtained by invoking the903* {@link TemporalAdjuster#adjustInto(Temporal)} method on the904* specified adjuster passing {@code this} as the argument.905* <p>906* This instance is immutable and unaffected by this method call.907*908* @param adjuster the adjuster to use, not null909* @return a {@code LocalDateTime} based on {@code this} with the adjustment made, not null910* @throws DateTimeException if the adjustment cannot be made911* @throws ArithmeticException if numeric overflow occurs912*/913@Override914public LocalDateTime with(TemporalAdjuster adjuster) {915// optimizations916if (adjuster instanceof LocalDate) {917return with((LocalDate) adjuster, time);918} else if (adjuster instanceof LocalTime) {919return with(date, (LocalTime) adjuster);920} else if (adjuster instanceof LocalDateTime) {921return (LocalDateTime) adjuster;922}923return (LocalDateTime) adjuster.adjustInto(this);924}925926/**927* Returns a copy of this date-time with the specified field set to a new value.928* <p>929* This returns a {@code LocalDateTime}, based on this one, with the value930* for the specified field changed.931* This can be used to change any supported field, such as the year, month or day-of-month.932* If it is not possible to set the value, because the field is not supported or for933* some other reason, an exception is thrown.934* <p>935* In some cases, changing the specified field can cause the resulting date-time to become invalid,936* such as changing the month from 31st January to February would make the day-of-month invalid.937* In cases like this, the field is responsible for resolving the date. Typically it will choose938* the previous valid date, which would be the last valid day of February in this example.939* <p>940* If the field is a {@link ChronoField} then the adjustment is implemented here.941* The {@link #isSupported(TemporalField) supported fields} will behave as per942* the matching method on {@link LocalDate#with(TemporalField, long) LocalDate}943* or {@link LocalTime#with(TemporalField, long) LocalTime}.944* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.945* <p>946* If the field is not a {@code ChronoField}, then the result of this method947* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}948* passing {@code this} as the argument. In this case, the field determines949* whether and how to adjust the instant.950* <p>951* This instance is immutable and unaffected by this method call.952*953* @param field the field to set in the result, not null954* @param newValue the new value of the field in the result955* @return a {@code LocalDateTime} based on {@code this} with the specified field set, not null956* @throws DateTimeException if the field cannot be set957* @throws UnsupportedTemporalTypeException if the field is not supported958* @throws ArithmeticException if numeric overflow occurs959*/960@Override961public LocalDateTime with(TemporalField field, long newValue) {962if (field instanceof ChronoField chronoField) {963if (chronoField.isTimeBased()) {964return with(date, time.with(field, newValue));965} else {966return with(date.with(field, newValue), time);967}968}969return field.adjustInto(this, newValue);970}971972//-----------------------------------------------------------------------973/**974* Returns a copy of this {@code LocalDateTime} with the year altered.975* <p>976* The time does not affect the calculation and will be the same in the result.977* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.978* <p>979* This instance is immutable and unaffected by this method call.980*981* @param year the year to set in the result, from MIN_YEAR to MAX_YEAR982* @return a {@code LocalDateTime} based on this date-time with the requested year, not null983* @throws DateTimeException if the year value is invalid984*/985public LocalDateTime withYear(int year) {986return with(date.withYear(year), time);987}988989/**990* Returns a copy of this {@code LocalDateTime} with the month-of-year altered.991* <p>992* The time does not affect the calculation and will be the same in the result.993* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.994* <p>995* This instance is immutable and unaffected by this method call.996*997* @param month the month-of-year to set in the result, from 1 (January) to 12 (December)998* @return a {@code LocalDateTime} based on this date-time with the requested month, not null999* @throws DateTimeException if the month-of-year value is invalid1000*/1001public LocalDateTime withMonth(int month) {1002return with(date.withMonth(month), time);1003}10041005/**1006* Returns a copy of this {@code LocalDateTime} with the day-of-month altered.1007* <p>1008* If the resulting date-time is invalid, an exception is thrown.1009* The time does not affect the calculation and will be the same in the result.1010* <p>1011* This instance is immutable and unaffected by this method call.1012*1013* @param dayOfMonth the day-of-month to set in the result, from 1 to 28-311014* @return a {@code LocalDateTime} based on this date-time with the requested day, not null1015* @throws DateTimeException if the day-of-month value is invalid,1016* or if the day-of-month is invalid for the month-year1017*/1018public LocalDateTime withDayOfMonth(int dayOfMonth) {1019return with(date.withDayOfMonth(dayOfMonth), time);1020}10211022/**1023* Returns a copy of this {@code LocalDateTime} with the day-of-year altered.1024* <p>1025* If the resulting date-time is invalid, an exception is thrown.1026* <p>1027* This instance is immutable and unaffected by this method call.1028*1029* @param dayOfYear the day-of-year to set in the result, from 1 to 365-3661030* @return a {@code LocalDateTime} based on this date with the requested day, not null1031* @throws DateTimeException if the day-of-year value is invalid,1032* or if the day-of-year is invalid for the year1033*/1034public LocalDateTime withDayOfYear(int dayOfYear) {1035return with(date.withDayOfYear(dayOfYear), time);1036}10371038//-----------------------------------------------------------------------1039/**1040* Returns a copy of this {@code LocalDateTime} with the hour-of-day altered.1041* <p>1042* This instance is immutable and unaffected by this method call.1043*1044* @param hour the hour-of-day to set in the result, from 0 to 231045* @return a {@code LocalDateTime} based on this date-time with the requested hour, not null1046* @throws DateTimeException if the hour value is invalid1047*/1048public LocalDateTime withHour(int hour) {1049LocalTime newTime = time.withHour(hour);1050return with(date, newTime);1051}10521053/**1054* Returns a copy of this {@code LocalDateTime} with the minute-of-hour altered.1055* <p>1056* This instance is immutable and unaffected by this method call.1057*1058* @param minute the minute-of-hour to set in the result, from 0 to 591059* @return a {@code LocalDateTime} based on this date-time with the requested minute, not null1060* @throws DateTimeException if the minute value is invalid1061*/1062public LocalDateTime withMinute(int minute) {1063LocalTime newTime = time.withMinute(minute);1064return with(date, newTime);1065}10661067/**1068* Returns a copy of this {@code LocalDateTime} with the second-of-minute altered.1069* <p>1070* This instance is immutable and unaffected by this method call.1071*1072* @param second the second-of-minute to set in the result, from 0 to 591073* @return a {@code LocalDateTime} based on this date-time with the requested second, not null1074* @throws DateTimeException if the second value is invalid1075*/1076public LocalDateTime withSecond(int second) {1077LocalTime newTime = time.withSecond(second);1078return with(date, newTime);1079}10801081/**1082* Returns a copy of this {@code LocalDateTime} with the nano-of-second altered.1083* <p>1084* This instance is immutable and unaffected by this method call.1085*1086* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,9991087* @return a {@code LocalDateTime} based on this date-time with the requested nanosecond, not null1088* @throws DateTimeException if the nano value is invalid1089*/1090public LocalDateTime withNano(int nanoOfSecond) {1091LocalTime newTime = time.withNano(nanoOfSecond);1092return with(date, newTime);1093}10941095//-----------------------------------------------------------------------1096/**1097* Returns a copy of this {@code LocalDateTime} with the time truncated.1098* <p>1099* Truncation returns a copy of the original date-time with fields1100* smaller than the specified unit set to zero.1101* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit1102* will set the second-of-minute and nano-of-second field to zero.1103* <p>1104* The unit must have a {@linkplain TemporalUnit#getDuration() duration}1105* that divides into the length of a standard day without remainder.1106* This includes all supplied time units on {@link ChronoUnit} and1107* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.1108* <p>1109* This instance is immutable and unaffected by this method call.1110*1111* @param unit the unit to truncate to, not null1112* @return a {@code LocalDateTime} based on this date-time with the time truncated, not null1113* @throws DateTimeException if unable to truncate1114* @throws UnsupportedTemporalTypeException if the unit is not supported1115*/1116public LocalDateTime truncatedTo(TemporalUnit unit) {1117return with(date, time.truncatedTo(unit));1118}11191120//-----------------------------------------------------------------------1121/**1122* Returns a copy of this date-time with the specified amount added.1123* <p>1124* This returns a {@code LocalDateTime}, based on this one, with the specified amount added.1125* The amount is typically {@link Period} or {@link Duration} but may be1126* any other type implementing the {@link TemporalAmount} interface.1127* <p>1128* The calculation is delegated to the amount object by calling1129* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free1130* to implement the addition in any way it wishes, however it typically1131* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation1132* of the amount implementation to determine if it can be successfully added.1133* <p>1134* This instance is immutable and unaffected by this method call.1135*1136* @param amountToAdd the amount to add, not null1137* @return a {@code LocalDateTime} based on this date-time with the addition made, not null1138* @throws DateTimeException if the addition cannot be made1139* @throws ArithmeticException if numeric overflow occurs1140*/1141@Override1142public LocalDateTime plus(TemporalAmount amountToAdd) {1143if (amountToAdd instanceof Period periodToAdd) {1144return with(date.plus(periodToAdd), time);1145}1146Objects.requireNonNull(amountToAdd, "amountToAdd");1147return (LocalDateTime) amountToAdd.addTo(this);1148}11491150/**1151* Returns a copy of this date-time with the specified amount added.1152* <p>1153* This returns a {@code LocalDateTime}, based on this one, with the amount1154* in terms of the unit added. If it is not possible to add the amount, because the1155* unit is not supported or for some other reason, an exception is thrown.1156* <p>1157* If the field is a {@link ChronoUnit} then the addition is implemented here.1158* Date units are added as per {@link LocalDate#plus(long, TemporalUnit)}.1159* Time units are added as per {@link LocalTime#plus(long, TemporalUnit)} with1160* any overflow in days added equivalent to using {@link #plusDays(long)}.1161* <p>1162* If the field is not a {@code ChronoUnit}, then the result of this method1163* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}1164* passing {@code this} as the argument. In this case, the unit determines1165* whether and how to perform the addition.1166* <p>1167* This instance is immutable and unaffected by this method call.1168*1169* @param amountToAdd the amount of the unit to add to the result, may be negative1170* @param unit the unit of the amount to add, not null1171* @return a {@code LocalDateTime} based on this date-time with the specified amount added, not null1172* @throws DateTimeException if the addition cannot be made1173* @throws UnsupportedTemporalTypeException if the unit is not supported1174* @throws ArithmeticException if numeric overflow occurs1175*/1176@Override1177public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {1178if (unit instanceof ChronoUnit chronoUnit) {1179switch (chronoUnit) {1180case NANOS: return plusNanos(amountToAdd);1181case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);1182case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);1183case SECONDS: return plusSeconds(amountToAdd);1184case MINUTES: return plusMinutes(amountToAdd);1185case HOURS: return plusHours(amountToAdd);1186case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)1187}1188return with(date.plus(amountToAdd, unit), time);1189}1190return unit.addTo(this, amountToAdd);1191}11921193//-----------------------------------------------------------------------1194/**1195* Returns a copy of this {@code LocalDateTime} with the specified number of years added.1196* <p>1197* This method adds the specified amount to the years field in three steps:1198* <ol>1199* <li>Add the input years to the year field</li>1200* <li>Check if the resulting date would be invalid</li>1201* <li>Adjust the day-of-month to the last valid day if necessary</li>1202* </ol>1203* <p>1204* For example, 2008-02-29 (leap year) plus one year would result in the1205* invalid date 2009-02-29 (standard year). Instead of returning an invalid1206* result, the last valid day of the month, 2009-02-28, is selected instead.1207* <p>1208* This instance is immutable and unaffected by this method call.1209*1210* @param years the years to add, may be negative1211* @return a {@code LocalDateTime} based on this date-time with the years added, not null1212* @throws DateTimeException if the result exceeds the supported date range1213*/1214public LocalDateTime plusYears(long years) {1215LocalDate newDate = date.plusYears(years);1216return with(newDate, time);1217}12181219/**1220* Returns a copy of this {@code LocalDateTime} with the specified number of months added.1221* <p>1222* This method adds the specified amount to the months field in three steps:1223* <ol>1224* <li>Add the input months to the month-of-year field</li>1225* <li>Check if the resulting date would be invalid</li>1226* <li>Adjust the day-of-month to the last valid day if necessary</li>1227* </ol>1228* <p>1229* For example, 2007-03-31 plus one month would result in the invalid date1230* 2007-04-31. Instead of returning an invalid result, the last valid day1231* of the month, 2007-04-30, is selected instead.1232* <p>1233* This instance is immutable and unaffected by this method call.1234*1235* @param months the months to add, may be negative1236* @return a {@code LocalDateTime} based on this date-time with the months added, not null1237* @throws DateTimeException if the result exceeds the supported date range1238*/1239public LocalDateTime plusMonths(long months) {1240LocalDate newDate = date.plusMonths(months);1241return with(newDate, time);1242}12431244/**1245* Returns a copy of this {@code LocalDateTime} with the specified number of weeks added.1246* <p>1247* This method adds the specified amount in weeks to the days field incrementing1248* the month and year fields as necessary to ensure the result remains valid.1249* The result is only invalid if the maximum/minimum year is exceeded.1250* <p>1251* For example, 2008-12-31 plus one week would result in 2009-01-07.1252* <p>1253* This instance is immutable and unaffected by this method call.1254*1255* @param weeks the weeks to add, may be negative1256* @return a {@code LocalDateTime} based on this date-time with the weeks added, not null1257* @throws DateTimeException if the result exceeds the supported date range1258*/1259public LocalDateTime plusWeeks(long weeks) {1260LocalDate newDate = date.plusWeeks(weeks);1261return with(newDate, time);1262}12631264/**1265* Returns a copy of this {@code LocalDateTime} with the specified number of days added.1266* <p>1267* This method adds the specified amount to the days field incrementing the1268* month and year fields as necessary to ensure the result remains valid.1269* The result is only invalid if the maximum/minimum year is exceeded.1270* <p>1271* For example, 2008-12-31 plus one day would result in 2009-01-01.1272* <p>1273* This instance is immutable and unaffected by this method call.1274*1275* @param days the days to add, may be negative1276* @return a {@code LocalDateTime} based on this date-time with the days added, not null1277* @throws DateTimeException if the result exceeds the supported date range1278*/1279public LocalDateTime plusDays(long days) {1280LocalDate newDate = date.plusDays(days);1281return with(newDate, time);1282}12831284//-----------------------------------------------------------------------1285/**1286* Returns a copy of this {@code LocalDateTime} with the specified number of hours added.1287* <p>1288* This instance is immutable and unaffected by this method call.1289*1290* @param hours the hours to add, may be negative1291* @return a {@code LocalDateTime} based on this date-time with the hours added, not null1292* @throws DateTimeException if the result exceeds the supported date range1293*/1294public LocalDateTime plusHours(long hours) {1295return plusWithOverflow(date, hours, 0, 0, 0, 1);1296}12971298/**1299* Returns a copy of this {@code LocalDateTime} with the specified number of minutes added.1300* <p>1301* This instance is immutable and unaffected by this method call.1302*1303* @param minutes the minutes to add, may be negative1304* @return a {@code LocalDateTime} based on this date-time with the minutes added, not null1305* @throws DateTimeException if the result exceeds the supported date range1306*/1307public LocalDateTime plusMinutes(long minutes) {1308return plusWithOverflow(date, 0, minutes, 0, 0, 1);1309}13101311/**1312* Returns a copy of this {@code LocalDateTime} with the specified number of seconds added.1313* <p>1314* This instance is immutable and unaffected by this method call.1315*1316* @param seconds the seconds to add, may be negative1317* @return a {@code LocalDateTime} based on this date-time with the seconds added, not null1318* @throws DateTimeException if the result exceeds the supported date range1319*/1320public LocalDateTime plusSeconds(long seconds) {1321return plusWithOverflow(date, 0, 0, seconds, 0, 1);1322}13231324/**1325* Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds added.1326* <p>1327* This instance is immutable and unaffected by this method call.1328*1329* @param nanos the nanos to add, may be negative1330* @return a {@code LocalDateTime} based on this date-time with the nanoseconds added, not null1331* @throws DateTimeException if the result exceeds the supported date range1332*/1333public LocalDateTime plusNanos(long nanos) {1334return plusWithOverflow(date, 0, 0, 0, nanos, 1);1335}13361337//-----------------------------------------------------------------------1338/**1339* Returns a copy of this date-time with the specified amount subtracted.1340* <p>1341* This returns a {@code LocalDateTime}, based on this one, with the specified amount subtracted.1342* The amount is typically {@link Period} or {@link Duration} but may be1343* any other type implementing the {@link TemporalAmount} interface.1344* <p>1345* The calculation is delegated to the amount object by calling1346* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free1347* to implement the subtraction in any way it wishes, however it typically1348* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation1349* of the amount implementation to determine if it can be successfully subtracted.1350* <p>1351* This instance is immutable and unaffected by this method call.1352*1353* @param amountToSubtract the amount to subtract, not null1354* @return a {@code LocalDateTime} based on this date-time with the subtraction made, not null1355* @throws DateTimeException if the subtraction cannot be made1356* @throws ArithmeticException if numeric overflow occurs1357*/1358@Override1359public LocalDateTime minus(TemporalAmount amountToSubtract) {1360if (amountToSubtract instanceof Period periodToSubtract) {1361return with(date.minus(periodToSubtract), time);1362}1363Objects.requireNonNull(amountToSubtract, "amountToSubtract");1364return (LocalDateTime) amountToSubtract.subtractFrom(this);1365}13661367/**1368* Returns a copy of this date-time with the specified amount subtracted.1369* <p>1370* This returns a {@code LocalDateTime}, based on this one, with the amount1371* in terms of the unit subtracted. If it is not possible to subtract the amount,1372* because the unit is not supported or for some other reason, an exception is thrown.1373* <p>1374* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.1375* See that method for a full description of how addition, and thus subtraction, works.1376* <p>1377* This instance is immutable and unaffected by this method call.1378*1379* @param amountToSubtract the amount of the unit to subtract from the result, may be negative1380* @param unit the unit of the amount to subtract, not null1381* @return a {@code LocalDateTime} based on this date-time with the specified amount subtracted, not null1382* @throws DateTimeException if the subtraction cannot be made1383* @throws UnsupportedTemporalTypeException if the unit is not supported1384* @throws ArithmeticException if numeric overflow occurs1385*/1386@Override1387public LocalDateTime minus(long amountToSubtract, TemporalUnit unit) {1388return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));1389}13901391//-----------------------------------------------------------------------1392/**1393* Returns a copy of this {@code LocalDateTime} with the specified number of years subtracted.1394* <p>1395* This method subtracts the specified amount from the years field in three steps:1396* <ol>1397* <li>Subtract the input years from the year field</li>1398* <li>Check if the resulting date would be invalid</li>1399* <li>Adjust the day-of-month to the last valid day if necessary</li>1400* </ol>1401* <p>1402* For example, 2008-02-29 (leap year) minus one year would result in the1403* invalid date 2007-02-29 (standard year). Instead of returning an invalid1404* result, the last valid day of the month, 2007-02-28, is selected instead.1405* <p>1406* This instance is immutable and unaffected by this method call.1407*1408* @param years the years to subtract, may be negative1409* @return a {@code LocalDateTime} based on this date-time with the years subtracted, not null1410* @throws DateTimeException if the result exceeds the supported date range1411*/1412public LocalDateTime minusYears(long years) {1413return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));1414}14151416/**1417* Returns a copy of this {@code LocalDateTime} with the specified number of months subtracted.1418* <p>1419* This method subtracts the specified amount from the months field in three steps:1420* <ol>1421* <li>Subtract the input months from the month-of-year field</li>1422* <li>Check if the resulting date would be invalid</li>1423* <li>Adjust the day-of-month to the last valid day if necessary</li>1424* </ol>1425* <p>1426* For example, 2007-03-31 minus one month would result in the invalid date1427* 2007-02-31. Instead of returning an invalid result, the last valid day1428* of the month, 2007-02-28, is selected instead.1429* <p>1430* This instance is immutable and unaffected by this method call.1431*1432* @param months the months to subtract, may be negative1433* @return a {@code LocalDateTime} based on this date-time with the months subtracted, not null1434* @throws DateTimeException if the result exceeds the supported date range1435*/1436public LocalDateTime minusMonths(long months) {1437return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));1438}14391440/**1441* Returns a copy of this {@code LocalDateTime} with the specified number of weeks subtracted.1442* <p>1443* This method subtracts the specified amount in weeks from the days field decrementing1444* the month and year fields as necessary to ensure the result remains valid.1445* The result is only invalid if the maximum/minimum year is exceeded.1446* <p>1447* For example, 2009-01-07 minus one week would result in 2008-12-31.1448* <p>1449* This instance is immutable and unaffected by this method call.1450*1451* @param weeks the weeks to subtract, may be negative1452* @return a {@code LocalDateTime} based on this date-time with the weeks subtracted, not null1453* @throws DateTimeException if the result exceeds the supported date range1454*/1455public LocalDateTime minusWeeks(long weeks) {1456return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));1457}14581459/**1460* Returns a copy of this {@code LocalDateTime} with the specified number of days subtracted.1461* <p>1462* This method subtracts the specified amount from the days field decrementing the1463* month and year fields as necessary to ensure the result remains valid.1464* The result is only invalid if the maximum/minimum year is exceeded.1465* <p>1466* For example, 2009-01-01 minus one day would result in 2008-12-31.1467* <p>1468* This instance is immutable and unaffected by this method call.1469*1470* @param days the days to subtract, may be negative1471* @return a {@code LocalDateTime} based on this date-time with the days subtracted, not null1472* @throws DateTimeException if the result exceeds the supported date range1473*/1474public LocalDateTime minusDays(long days) {1475return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));1476}14771478//-----------------------------------------------------------------------1479/**1480* Returns a copy of this {@code LocalDateTime} with the specified number of hours subtracted.1481* <p>1482* This instance is immutable and unaffected by this method call.1483*1484* @param hours the hours to subtract, may be negative1485* @return a {@code LocalDateTime} based on this date-time with the hours subtracted, not null1486* @throws DateTimeException if the result exceeds the supported date range1487*/1488public LocalDateTime minusHours(long hours) {1489return plusWithOverflow(date, hours, 0, 0, 0, -1);1490}14911492/**1493* Returns a copy of this {@code LocalDateTime} with the specified number of minutes subtracted.1494* <p>1495* This instance is immutable and unaffected by this method call.1496*1497* @param minutes the minutes to subtract, may be negative1498* @return a {@code LocalDateTime} based on this date-time with the minutes subtracted, not null1499* @throws DateTimeException if the result exceeds the supported date range1500*/1501public LocalDateTime minusMinutes(long minutes) {1502return plusWithOverflow(date, 0, minutes, 0, 0, -1);1503}15041505/**1506* Returns a copy of this {@code LocalDateTime} with the specified number of seconds subtracted.1507* <p>1508* This instance is immutable and unaffected by this method call.1509*1510* @param seconds the seconds to subtract, may be negative1511* @return a {@code LocalDateTime} based on this date-time with the seconds subtracted, not null1512* @throws DateTimeException if the result exceeds the supported date range1513*/1514public LocalDateTime minusSeconds(long seconds) {1515return plusWithOverflow(date, 0, 0, seconds, 0, -1);1516}15171518/**1519* Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds subtracted.1520* <p>1521* This instance is immutable and unaffected by this method call.1522*1523* @param nanos the nanos to subtract, may be negative1524* @return a {@code LocalDateTime} based on this date-time with the nanoseconds subtracted, not null1525* @throws DateTimeException if the result exceeds the supported date range1526*/1527public LocalDateTime minusNanos(long nanos) {1528return plusWithOverflow(date, 0, 0, 0, nanos, -1);1529}15301531//-----------------------------------------------------------------------1532/**1533* Returns a copy of this {@code LocalDateTime} with the specified period added.1534* <p>1535* This instance is immutable and unaffected by this method call.1536*1537* @param newDate the new date to base the calculation on, not null1538* @param hours the hours to add, may be negative1539* @param minutes the minutes to add, may be negative1540* @param seconds the seconds to add, may be negative1541* @param nanos the nanos to add, may be negative1542* @param sign the sign to determine add or subtract1543* @return the combined result, not null1544*/1545private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, long nanos, int sign) {1546// 9223372036854775808 long, 2147483648 int1547if ((hours | minutes | seconds | nanos) == 0) {1548return with(newDate, time);1549}1550long totDays = nanos / NANOS_PER_DAY + // max/24*60*60*1B1551seconds / SECONDS_PER_DAY + // max/24*60*601552minutes / MINUTES_PER_DAY + // max/24*601553hours / HOURS_PER_DAY; // max/241554totDays *= sign; // total max*0.4237...1555long totNanos = nanos % NANOS_PER_DAY + // max 864000000000001556(seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND + // max 864000000000001557(minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE + // max 864000000000001558(hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 864000000000001559long curNoD = time.toNanoOfDay(); // max 864000000000001560totNanos = totNanos * sign + curNoD; // total 4320000000000001561totDays += Math.floorDiv(totNanos, NANOS_PER_DAY);1562long newNoD = Math.floorMod(totNanos, NANOS_PER_DAY);1563LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD));1564return with(newDate.plusDays(totDays), newTime);1565}15661567//-----------------------------------------------------------------------1568/**1569* Queries this date-time using the specified query.1570* <p>1571* This queries this date-time using the specified query strategy object.1572* The {@code TemporalQuery} object defines the logic to be used to1573* obtain the result. Read the documentation of the query to understand1574* what the result of this method will be.1575* <p>1576* The result of this method is obtained by invoking the1577* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1578* specified query passing {@code this} as the argument.1579*1580* @param <R> the type of the result1581* @param query the query to invoke, not null1582* @return the query result, null may be returned (defined by the query)1583* @throws DateTimeException if unable to query (defined by the query)1584* @throws ArithmeticException if numeric overflow occurs (defined by the query)1585*/1586@SuppressWarnings("unchecked")1587@Override // override for Javadoc1588public <R> R query(TemporalQuery<R> query) {1589if (query == TemporalQueries.localDate()) {1590return (R) date;1591}1592return ChronoLocalDateTime.super.query(query);1593}15941595/**1596* Adjusts the specified temporal object to have the same date and time as this object.1597* <p>1598* This returns a temporal object of the same observable type as the input1599* with the date and time changed to be the same as this.1600* <p>1601* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1602* twice, passing {@link ChronoField#EPOCH_DAY} and1603* {@link ChronoField#NANO_OF_DAY} as the fields.1604* <p>1605* In most cases, it is clearer to reverse the calling pattern by using1606* {@link Temporal#with(TemporalAdjuster)}:1607* <pre>1608* // these two lines are equivalent, but the second approach is recommended1609* temporal = thisLocalDateTime.adjustInto(temporal);1610* temporal = temporal.with(thisLocalDateTime);1611* </pre>1612* <p>1613* This instance is immutable and unaffected by this method call.1614*1615* @param temporal the target object to be adjusted, not null1616* @return the adjusted object, not null1617* @throws DateTimeException if unable to make the adjustment1618* @throws ArithmeticException if numeric overflow occurs1619*/1620@Override // override for Javadoc1621public Temporal adjustInto(Temporal temporal) {1622return ChronoLocalDateTime.super.adjustInto(temporal);1623}16241625/**1626* Calculates the amount of time until another date-time in terms of the specified unit.1627* <p>1628* This calculates the amount of time between two {@code LocalDateTime}1629* objects in terms of a single {@code TemporalUnit}.1630* The start and end points are {@code this} and the specified date-time.1631* The result will be negative if the end is before the start.1632* The {@code Temporal} passed to this method is converted to a1633* {@code LocalDateTime} using {@link #from(TemporalAccessor)}.1634* For example, the amount in days between two date-times can be calculated1635* using {@code startDateTime.until(endDateTime, DAYS)}.1636* <p>1637* The calculation returns a whole number, representing the number of1638* complete units between the two date-times.1639* For example, the amount in months between 2012-06-15T00:00 and 2012-08-14T23:591640* will only be one month as it is one minute short of two months.1641* <p>1642* There are two equivalent ways of using this method.1643* The first is to invoke this method.1644* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1645* <pre>1646* // these two lines are equivalent1647* amount = start.until(end, MONTHS);1648* amount = MONTHS.between(start, end);1649* </pre>1650* The choice should be made based on which makes the code more readable.1651* <p>1652* The calculation is implemented in this method for {@link ChronoUnit}.1653* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1654* {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},1655* {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},1656* {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.1657* Other {@code ChronoUnit} values will throw an exception.1658* <p>1659* If the unit is not a {@code ChronoUnit}, then the result of this method1660* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1661* passing {@code this} as the first argument and the converted input temporal1662* as the second argument.1663* <p>1664* This instance is immutable and unaffected by this method call.1665*1666* @param endExclusive the end date, exclusive, which is converted to a {@code LocalDateTime}, not null1667* @param unit the unit to measure the amount in, not null1668* @return the amount of time between this date-time and the end date-time1669* @throws DateTimeException if the amount cannot be calculated, or the end1670* temporal cannot be converted to a {@code LocalDateTime}1671* @throws UnsupportedTemporalTypeException if the unit is not supported1672* @throws ArithmeticException if numeric overflow occurs1673*/1674@Override1675public long until(Temporal endExclusive, TemporalUnit unit) {1676LocalDateTime end = LocalDateTime.from(endExclusive);1677if (unit instanceof ChronoUnit chronoUnit) {1678if (unit.isTimeBased()) {1679long amount = date.daysUntil(end.date);1680if (amount == 0) {1681return time.until(end.time, unit);1682}1683long timePart = end.time.toNanoOfDay() - time.toNanoOfDay();1684if (amount > 0) {1685amount--; // safe1686timePart += NANOS_PER_DAY; // safe1687} else {1688amount++; // safe1689timePart -= NANOS_PER_DAY; // safe1690}1691switch (chronoUnit) {1692case NANOS:1693amount = Math.multiplyExact(amount, NANOS_PER_DAY);1694break;1695case MICROS:1696amount = Math.multiplyExact(amount, MICROS_PER_DAY);1697timePart = timePart / 1000;1698break;1699case MILLIS:1700amount = Math.multiplyExact(amount, MILLIS_PER_DAY);1701timePart = timePart / 1_000_000;1702break;1703case SECONDS:1704amount = Math.multiplyExact(amount, SECONDS_PER_DAY);1705timePart = timePart / NANOS_PER_SECOND;1706break;1707case MINUTES:1708amount = Math.multiplyExact(amount, MINUTES_PER_DAY);1709timePart = timePart / NANOS_PER_MINUTE;1710break;1711case HOURS:1712amount = Math.multiplyExact(amount, HOURS_PER_DAY);1713timePart = timePart / NANOS_PER_HOUR;1714break;1715case HALF_DAYS:1716amount = Math.multiplyExact(amount, 2);1717timePart = timePart / (NANOS_PER_HOUR * 12);1718break;1719}1720return Math.addExact(amount, timePart);1721}1722LocalDate endDate = end.date;1723if (endDate.isAfter(date) && end.time.isBefore(time)) {1724endDate = endDate.minusDays(1);1725} else if (endDate.isBefore(date) && end.time.isAfter(time)) {1726endDate = endDate.plusDays(1);1727}1728return date.until(endDate, unit);1729}1730return unit.between(this, end);1731}17321733/**1734* Formats this date-time using the specified formatter.1735* <p>1736* This date-time will be passed to the formatter to produce a string.1737*1738* @param formatter the formatter to use, not null1739* @return the formatted date-time string, not null1740* @throws DateTimeException if an error occurs during printing1741*/1742@Override // override for Javadoc and performance1743public String format(DateTimeFormatter formatter) {1744Objects.requireNonNull(formatter, "formatter");1745return formatter.format(this);1746}17471748//-----------------------------------------------------------------------1749/**1750* Combines this date-time with an offset to create an {@code OffsetDateTime}.1751* <p>1752* This returns an {@code OffsetDateTime} formed from this date-time at the specified offset.1753* All possible combinations of date-time and offset are valid.1754*1755* @param offset the offset to combine with, not null1756* @return the offset date-time formed from this date-time and the specified offset, not null1757*/1758public OffsetDateTime atOffset(ZoneOffset offset) {1759return OffsetDateTime.of(this, offset);1760}17611762/**1763* Combines this date-time with a time-zone to create a {@code ZonedDateTime}.1764* <p>1765* This returns a {@code ZonedDateTime} formed from this date-time at the1766* specified time-zone. The result will match this date-time as closely as possible.1767* Time-zone rules, such as daylight savings, mean that not every local date-time1768* is valid for the specified zone, thus the local date-time may be adjusted.1769* <p>1770* The local date-time is resolved to a single instant on the time-line.1771* This is achieved by finding a valid offset from UTC/Greenwich for the local1772* date-time as defined by the {@link ZoneRules rules} of the zone ID.1773*<p>1774* In most cases, there is only one valid offset for a local date-time.1775* In the case of an overlap, where clocks are set back, there are two valid offsets.1776* This method uses the earlier offset typically corresponding to "summer".1777* <p>1778* In the case of a gap, where clocks jump forward, there is no valid offset.1779* Instead, the local date-time is adjusted to be later by the length of the gap.1780* For a typical one hour daylight savings change, the local date-time will be1781* moved one hour later into the offset typically corresponding to "summer".1782* <p>1783* To obtain the later offset during an overlap, call1784* {@link ZonedDateTime#withLaterOffsetAtOverlap()} on the result of this method.1785* To throw an exception when there is a gap or overlap, use1786* {@link ZonedDateTime#ofStrict(LocalDateTime, ZoneOffset, ZoneId)}.1787*1788* @param zone the time-zone to use, not null1789* @return the zoned date-time formed from this date-time, not null1790*/1791@Override1792public ZonedDateTime atZone(ZoneId zone) {1793return ZonedDateTime.of(this, zone);1794}17951796//-----------------------------------------------------------------------1797/**1798* Compares this date-time to another date-time.1799* <p>1800* The comparison is primarily based on the date-time, from earliest to latest.1801* It is "consistent with equals", as defined by {@link Comparable}.1802* <p>1803* If all the date-times being compared are instances of {@code LocalDateTime},1804* then the comparison will be entirely based on the date-time.1805* If some dates being compared are in different chronologies, then the1806* chronology is also considered, see {@link ChronoLocalDateTime#compareTo}.1807*1808* @param other the other date-time to compare to, not null1809* @return the comparator value, negative if less, positive if greater1810*/1811@Override // override for Javadoc and performance1812public int compareTo(ChronoLocalDateTime<?> other) {1813if (other instanceof LocalDateTime) {1814return compareTo0((LocalDateTime) other);1815}1816return ChronoLocalDateTime.super.compareTo(other);1817}18181819private int compareTo0(LocalDateTime other) {1820int cmp = date.compareTo0(other.toLocalDate());1821if (cmp == 0) {1822cmp = time.compareTo(other.toLocalTime());1823}1824return cmp;1825}18261827/**1828* Checks if this date-time is after the specified date-time.1829* <p>1830* This checks to see if this date-time represents a point on the1831* local time-line after the other date-time.1832* <pre>1833* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1834* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1835* a.isAfter(b) == false1836* a.isAfter(a) == false1837* b.isAfter(a) == true1838* </pre>1839* <p>1840* This method only considers the position of the two date-times on the local time-line.1841* It does not take into account the chronology, or calendar system.1842* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1843* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1844*1845* @param other the other date-time to compare to, not null1846* @return true if this date-time is after the specified date-time1847*/1848@Override // override for Javadoc and performance1849public boolean isAfter(ChronoLocalDateTime<?> other) {1850if (other instanceof LocalDateTime) {1851return compareTo0((LocalDateTime) other) > 0;1852}1853return ChronoLocalDateTime.super.isAfter(other);1854}18551856/**1857* Checks if this date-time is before the specified date-time.1858* <p>1859* This checks to see if this date-time represents a point on the1860* local time-line before the other date-time.1861* <pre>1862* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1863* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1864* a.isBefore(b) == true1865* a.isBefore(a) == false1866* b.isBefore(a) == false1867* </pre>1868* <p>1869* This method only considers the position of the two date-times on the local time-line.1870* It does not take into account the chronology, or calendar system.1871* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1872* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1873*1874* @param other the other date-time to compare to, not null1875* @return true if this date-time is before the specified date-time1876*/1877@Override // override for Javadoc and performance1878public boolean isBefore(ChronoLocalDateTime<?> other) {1879if (other instanceof LocalDateTime) {1880return compareTo0((LocalDateTime) other) < 0;1881}1882return ChronoLocalDateTime.super.isBefore(other);1883}18841885/**1886* Checks if this date-time is equal to the specified date-time.1887* <p>1888* This checks to see if this date-time represents the same point on the1889* local time-line as the other date-time.1890* <pre>1891* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1892* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1893* a.isEqual(b) == false1894* a.isEqual(a) == true1895* b.isEqual(a) == false1896* </pre>1897* <p>1898* This method only considers the position of the two date-times on the local time-line.1899* It does not take into account the chronology, or calendar system.1900* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1901* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1902*1903* @param other the other date-time to compare to, not null1904* @return true if this date-time is equal to the specified date-time1905*/1906@Override // override for Javadoc and performance1907public boolean isEqual(ChronoLocalDateTime<?> other) {1908if (other instanceof LocalDateTime) {1909return compareTo0((LocalDateTime) other) == 0;1910}1911return ChronoLocalDateTime.super.isEqual(other);1912}19131914//-----------------------------------------------------------------------1915/**1916* Checks if this date-time is equal to another date-time.1917* <p>1918* Compares this {@code LocalDateTime} with another ensuring that the date-time is the same.1919* Only objects of type {@code LocalDateTime} are compared, other types return false.1920*1921* @param obj the object to check, null returns false1922* @return true if this is equal to the other date-time1923*/1924@Override1925public boolean equals(Object obj) {1926if (this == obj) {1927return true;1928}1929return (obj instanceof LocalDateTime other)1930&& date.equals(other.date)1931&& time.equals(other.time);1932}19331934/**1935* A hash code for this date-time.1936*1937* @return a suitable hash code1938*/1939@Override1940public int hashCode() {1941return date.hashCode() ^ time.hashCode();1942}19431944//-----------------------------------------------------------------------1945/**1946* Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}.1947* <p>1948* The output will be one of the following ISO-8601 formats:1949* <ul>1950* <li>{@code uuuu-MM-dd'T'HH:mm}</li>1951* <li>{@code uuuu-MM-dd'T'HH:mm:ss}</li>1952* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSS}</li>1953* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSS}</li>1954* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS}</li>1955* </ul>1956* The format used will be the shortest that outputs the full value of1957* the time where the omitted parts are implied to be zero.1958*1959* @return a string representation of this date-time, not null1960*/1961@Override1962public String toString() {1963return date.toString() + 'T' + time.toString();1964}19651966//-----------------------------------------------------------------------1967/**1968* Writes the object using a1969* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1970* @serialData1971* <pre>1972* out.writeByte(5); // identifies a LocalDateTime1973* // the <a href="{@docRoot}/serialized-form.html#java.time.LocalDate">date</a> excluding the one byte header1974* // the <a href="{@docRoot}/serialized-form.html#java.time.LocalTime">time</a> excluding the one byte header1975* </pre>1976*1977* @return the instance of {@code Ser}, not null1978*/1979@java.io.Serial1980private Object writeReplace() {1981return new Ser(Ser.LOCAL_DATE_TIME_TYPE, this);1982}19831984/**1985* Defend against malicious streams.1986*1987* @param s the stream to read1988* @throws InvalidObjectException always1989*/1990@java.io.Serial1991private void readObject(ObjectInputStream s) throws InvalidObjectException {1992throw new InvalidObjectException("Deserialization via serialization delegate");1993}19941995void writeExternal(DataOutput out) throws IOException {1996date.writeExternal(out);1997time.writeExternal(out);1998}19992000static LocalDateTime readExternal(DataInput in) throws IOException {2001LocalDate date = LocalDate.readExternal(in);2002LocalTime time = LocalTime.readExternal(in);2003return LocalDateTime.of(date, time);2004}20052006}200720082009