Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/LocalDateTime.java
38829 views
/*1* Copyright (c) 2012, 2015, 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*122* <p>123* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>124* class; use of identity-sensitive operations (including reference equality125* ({@code ==}), identity hash code, or synchronization) on instances of126* {@code LocalDateTime} may have unpredictable results and should be avoided.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*/134public final class LocalDateTime135implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {136137/**138* The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'.139* This is the local date-time of midnight at the start of the minimum date.140* This combines {@link LocalDate#MIN} and {@link LocalTime#MIN}.141* This could be used by an application as a "far past" date-time.142*/143public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN);144/**145* The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'.146* This is the local date-time just before midnight at the end of the maximum date.147* This combines {@link LocalDate#MAX} and {@link LocalTime#MAX}.148* This could be used by an application as a "far future" date-time.149*/150public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX);151152/**153* Serialization version.154*/155private static final long serialVersionUID = 6207766400415563566L;156157/**158* The date part.159*/160private final LocalDate date;161/**162* The time part.163*/164private final LocalTime time;165166//-----------------------------------------------------------------------167/**168* Obtains the current date-time from the system clock in the default time-zone.169* <p>170* This will query the {@link Clock#systemDefaultZone() system clock} in the default171* time-zone to obtain the current date-time.172* <p>173* Using this method will prevent the ability to use an alternate clock for testing174* because the clock is hard-coded.175*176* @return the current date-time using the system clock and default time-zone, not null177*/178public static LocalDateTime now() {179return now(Clock.systemDefaultZone());180}181182/**183* Obtains the current date-time from the system clock in the specified time-zone.184* <p>185* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.186* Specifying the time-zone avoids dependence on the default time-zone.187* <p>188* Using this method will prevent the ability to use an alternate clock for testing189* because the clock is hard-coded.190*191* @param zone the zone ID to use, not null192* @return the current date-time using the system clock, not null193*/194public static LocalDateTime now(ZoneId zone) {195return now(Clock.system(zone));196}197198/**199* Obtains the current date-time from the specified clock.200* <p>201* This will query the specified clock to obtain the current date-time.202* Using this method allows the use of an alternate clock for testing.203* The alternate clock may be introduced using {@link Clock dependency injection}.204*205* @param clock the clock to use, not null206* @return the current date-time, not null207*/208public static LocalDateTime now(Clock clock) {209Objects.requireNonNull(clock, "clock");210final Instant now = clock.instant(); // called once211ZoneOffset offset = clock.getZone().getRules().getOffset(now);212return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);213}214215//-----------------------------------------------------------------------216/**217* Obtains an instance of {@code LocalDateTime} from year, month,218* day, hour and minute, setting the second and nanosecond to zero.219* <p>220* This returns a {@code LocalDateTime} with the specified year, month,221* day-of-month, hour and minute.222* The day must be valid for the year and month, otherwise an exception will be thrown.223* The second and nanosecond fields will be set to zero.224*225* @param year the year to represent, from MIN_YEAR to MAX_YEAR226* @param month the month-of-year to represent, not null227* @param dayOfMonth the day-of-month to represent, from 1 to 31228* @param hour the hour-of-day to represent, from 0 to 23229* @param minute the minute-of-hour to represent, from 0 to 59230* @return the local date-time, not null231* @throws DateTimeException if the value of any field is out of range,232* or if the day-of-month is invalid for the month-year233*/234public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {235LocalDate date = LocalDate.of(year, month, dayOfMonth);236LocalTime time = LocalTime.of(hour, minute);237return new LocalDateTime(date, time);238}239240/**241* Obtains an instance of {@code LocalDateTime} from year, month,242* day, hour, minute and second, setting the nanosecond to zero.243* <p>244* This returns a {@code LocalDateTime} with the specified year, month,245* day-of-month, hour, minute and second.246* The day must be valid for the year and month, otherwise an exception will be thrown.247* The nanosecond field will be set to zero.248*249* @param year the year to represent, from MIN_YEAR to MAX_YEAR250* @param month the month-of-year to represent, not null251* @param dayOfMonth the day-of-month to represent, from 1 to 31252* @param hour the hour-of-day to represent, from 0 to 23253* @param minute the minute-of-hour to represent, from 0 to 59254* @param second the second-of-minute to represent, from 0 to 59255* @return the local date-time, not null256* @throws DateTimeException if the value of any field is out of range,257* or if the day-of-month is invalid for the month-year258*/259public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) {260LocalDate date = LocalDate.of(year, month, dayOfMonth);261LocalTime time = LocalTime.of(hour, minute, second);262return new LocalDateTime(date, time);263}264265/**266* Obtains an instance of {@code LocalDateTime} from year, month,267* day, hour, minute, second and nanosecond.268* <p>269* This returns a {@code LocalDateTime} with the specified year, month,270* day-of-month, hour, minute, second and nanosecond.271* The day must be valid for the year and month, otherwise an exception will be thrown.272*273* @param year the year to represent, from MIN_YEAR to MAX_YEAR274* @param month the month-of-year to represent, not null275* @param dayOfMonth the day-of-month to represent, from 1 to 31276* @param hour the hour-of-day to represent, from 0 to 23277* @param minute the minute-of-hour to represent, from 0 to 59278* @param second the second-of-minute to represent, from 0 to 59279* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999280* @return the local date-time, not null281* @throws DateTimeException if the value of any field is out of range,282* or if the day-of-month is invalid for the month-year283*/284public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {285LocalDate date = LocalDate.of(year, month, dayOfMonth);286LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);287return new LocalDateTime(date, time);288}289290//-----------------------------------------------------------------------291/**292* Obtains an instance of {@code LocalDateTime} from year, month,293* day, hour and minute, setting the second and nanosecond to zero.294* <p>295* This returns a {@code LocalDateTime} with the specified year, month,296* day-of-month, hour and minute.297* The day must be valid for the year and month, otherwise an exception will be thrown.298* The second and nanosecond fields will be set to zero.299*300* @param year the year to represent, from MIN_YEAR to MAX_YEAR301* @param month the month-of-year to represent, from 1 (January) to 12 (December)302* @param dayOfMonth the day-of-month to represent, from 1 to 31303* @param hour the hour-of-day to represent, from 0 to 23304* @param minute the minute-of-hour to represent, from 0 to 59305* @return the local date-time, not null306* @throws DateTimeException if the value of any field is out of range,307* or if the day-of-month is invalid for the month-year308*/309public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) {310LocalDate date = LocalDate.of(year, month, dayOfMonth);311LocalTime time = LocalTime.of(hour, minute);312return new LocalDateTime(date, time);313}314315/**316* Obtains an instance of {@code LocalDateTime} from year, month,317* day, hour, minute and second, setting the nanosecond to zero.318* <p>319* This returns a {@code LocalDateTime} with the specified year, month,320* day-of-month, hour, minute and second.321* The day must be valid for the year and month, otherwise an exception will be thrown.322* The nanosecond field will be set to zero.323*324* @param year the year to represent, from MIN_YEAR to MAX_YEAR325* @param month the month-of-year to represent, from 1 (January) to 12 (December)326* @param dayOfMonth the day-of-month to represent, from 1 to 31327* @param hour the hour-of-day to represent, from 0 to 23328* @param minute the minute-of-hour to represent, from 0 to 59329* @param second the second-of-minute to represent, from 0 to 59330* @return the local date-time, not null331* @throws DateTimeException if the value of any field is out of range,332* or if the day-of-month is invalid for the month-year333*/334public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) {335LocalDate date = LocalDate.of(year, month, dayOfMonth);336LocalTime time = LocalTime.of(hour, minute, second);337return new LocalDateTime(date, time);338}339340/**341* Obtains an instance of {@code LocalDateTime} from year, month,342* day, hour, minute, second and nanosecond.343* <p>344* This returns a {@code LocalDateTime} with the specified year, month,345* day-of-month, hour, minute, second and nanosecond.346* The day must be valid for the year and month, otherwise an exception will be thrown.347*348* @param year the year to represent, from MIN_YEAR to MAX_YEAR349* @param month the month-of-year to represent, from 1 (January) to 12 (December)350* @param dayOfMonth the day-of-month to represent, from 1 to 31351* @param hour the hour-of-day to represent, from 0 to 23352* @param minute the minute-of-hour to represent, from 0 to 59353* @param second the second-of-minute to represent, from 0 to 59354* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,999355* @return the local date-time, not null356* @throws DateTimeException if the value of any field is out of range,357* or if the day-of-month is invalid for the month-year358*/359public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {360LocalDate date = LocalDate.of(year, month, dayOfMonth);361LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);362return new LocalDateTime(date, time);363}364365/**366* Obtains an instance of {@code LocalDateTime} from a date and time.367*368* @param date the local date, not null369* @param time the local time, not null370* @return the local date-time, not null371*/372public static LocalDateTime of(LocalDate date, LocalTime time) {373Objects.requireNonNull(date, "date");374Objects.requireNonNull(time, "time");375return new LocalDateTime(date, time);376}377378//-------------------------------------------------------------------------379/**380* Obtains an instance of {@code LocalDateTime} from an {@code Instant} and zone ID.381* <p>382* This creates a local date-time based on the specified instant.383* First, the offset from UTC/Greenwich is obtained using the zone ID and instant,384* which is simple as there is only one valid offset for each instant.385* Then, the instant and offset are used to calculate the local date-time.386*387* @param instant the instant to create the date-time from, not null388* @param zone the time-zone, which may be an offset, not null389* @return the local date-time, not null390* @throws DateTimeException if the result exceeds the supported range391*/392public static LocalDateTime ofInstant(Instant instant, ZoneId zone) {393Objects.requireNonNull(instant, "instant");394Objects.requireNonNull(zone, "zone");395ZoneRules rules = zone.getRules();396ZoneOffset offset = rules.getOffset(instant);397return ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);398}399400/**401* Obtains an instance of {@code LocalDateTime} using seconds from the402* epoch of 1970-01-01T00:00:00Z.403* <p>404* This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field405* to be converted to a local date-time. This is primarily intended for406* low-level conversions rather than general application usage.407*408* @param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z409* @param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999410* @param offset the zone offset, not null411* @return the local date-time, not null412* @throws DateTimeException if the result exceeds the supported range,413* or if the nano-of-second is invalid414*/415public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {416Objects.requireNonNull(offset, "offset");417NANO_OF_SECOND.checkValidValue(nanoOfSecond);418long localSecond = epochSecond + offset.getTotalSeconds(); // overflow caught later419long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);420int secsOfDay = (int)Math.floorMod(localSecond, SECONDS_PER_DAY);421LocalDate date = LocalDate.ofEpochDay(localEpochDay);422LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + nanoOfSecond);423return new LocalDateTime(date, time);424}425426//-----------------------------------------------------------------------427/**428* Obtains an instance of {@code LocalDateTime} from a temporal object.429* <p>430* This obtains a local date-time based on the specified temporal.431* A {@code TemporalAccessor} represents an arbitrary set of date and time information,432* which this factory converts to an instance of {@code LocalDateTime}.433* <p>434* The conversion extracts and combines the {@code LocalDate} and the435* {@code LocalTime} from the temporal object.436* Implementations are permitted to perform optimizations such as accessing437* those fields that are equivalent to the relevant objects.438* <p>439* This method matches the signature of the functional interface {@link TemporalQuery}440* allowing it to be used as a query via method reference, {@code LocalDateTime::from}.441*442* @param temporal the temporal object to convert, not null443* @return the local date-time, not null444* @throws DateTimeException if unable to convert to a {@code LocalDateTime}445*/446public static LocalDateTime from(TemporalAccessor temporal) {447if (temporal instanceof LocalDateTime) {448return (LocalDateTime) temporal;449} else if (temporal instanceof ZonedDateTime) {450return ((ZonedDateTime) temporal).toLocalDateTime();451} else if (temporal instanceof OffsetDateTime) {452return ((OffsetDateTime) temporal).toLocalDateTime();453}454try {455LocalDate date = LocalDate.from(temporal);456LocalTime time = LocalTime.from(temporal);457return new LocalDateTime(date, time);458} catch (DateTimeException ex) {459throw new DateTimeException("Unable to obtain LocalDateTime from TemporalAccessor: " +460temporal + " of type " + temporal.getClass().getName(), ex);461}462}463464//-----------------------------------------------------------------------465/**466* Obtains an instance of {@code LocalDateTime} from a text string such as {@code 2007-12-03T10:15:30}.467* <p>468* The string must represent a valid date-time and is parsed using469* {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE_TIME}.470*471* @param text the text to parse such as "2007-12-03T10:15:30", not null472* @return the parsed local date-time, not null473* @throws DateTimeParseException if the text cannot be parsed474*/475public static LocalDateTime parse(CharSequence text) {476return parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME);477}478479/**480* Obtains an instance of {@code LocalDateTime} from a text string using a specific formatter.481* <p>482* The text is parsed using the formatter, returning a date-time.483*484* @param text the text to parse, not null485* @param formatter the formatter to use, not null486* @return the parsed local date-time, not null487* @throws DateTimeParseException if the text cannot be parsed488*/489public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {490Objects.requireNonNull(formatter, "formatter");491return formatter.parse(text, LocalDateTime::from);492}493494//-----------------------------------------------------------------------495/**496* Constructor.497*498* @param date the date part of the date-time, validated not null499* @param time the time part of the date-time, validated not null500*/501private LocalDateTime(LocalDate date, LocalTime time) {502this.date = date;503this.time = time;504}505506/**507* Returns a copy of this date-time with the new date and time, checking508* to see if a new object is in fact required.509*510* @param newDate the date of the new date-time, not null511* @param newTime the time of the new date-time, not null512* @return the date-time, not null513*/514private LocalDateTime with(LocalDate newDate, LocalTime newTime) {515if (date == newDate && time == newTime) {516return this;517}518return new LocalDateTime(newDate, newTime);519}520521//-----------------------------------------------------------------------522/**523* Checks if the specified field is supported.524* <p>525* This checks if this date-time can be queried for the specified field.526* If false, then calling the {@link #range(TemporalField) range},527* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}528* methods will throw an exception.529* <p>530* If the field is a {@link ChronoField} then the query is implemented here.531* The supported fields are:532* <ul>533* <li>{@code NANO_OF_SECOND}534* <li>{@code NANO_OF_DAY}535* <li>{@code MICRO_OF_SECOND}536* <li>{@code MICRO_OF_DAY}537* <li>{@code MILLI_OF_SECOND}538* <li>{@code MILLI_OF_DAY}539* <li>{@code SECOND_OF_MINUTE}540* <li>{@code SECOND_OF_DAY}541* <li>{@code MINUTE_OF_HOUR}542* <li>{@code MINUTE_OF_DAY}543* <li>{@code HOUR_OF_AMPM}544* <li>{@code CLOCK_HOUR_OF_AMPM}545* <li>{@code HOUR_OF_DAY}546* <li>{@code CLOCK_HOUR_OF_DAY}547* <li>{@code AMPM_OF_DAY}548* <li>{@code DAY_OF_WEEK}549* <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}550* <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}551* <li>{@code DAY_OF_MONTH}552* <li>{@code DAY_OF_YEAR}553* <li>{@code EPOCH_DAY}554* <li>{@code ALIGNED_WEEK_OF_MONTH}555* <li>{@code ALIGNED_WEEK_OF_YEAR}556* <li>{@code MONTH_OF_YEAR}557* <li>{@code PROLEPTIC_MONTH}558* <li>{@code YEAR_OF_ERA}559* <li>{@code YEAR}560* <li>{@code ERA}561* </ul>562* All other {@code ChronoField} instances will return false.563* <p>564* If the field is not a {@code ChronoField}, then the result of this method565* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}566* passing {@code this} as the argument.567* Whether the field is supported is determined by the field.568*569* @param field the field to check, null returns false570* @return true if the field is supported on this date-time, false if not571*/572@Override573public boolean isSupported(TemporalField field) {574if (field instanceof ChronoField) {575ChronoField f = (ChronoField) field;576return f.isDateBased() || f.isTimeBased();577}578return field != null && field.isSupportedBy(this);579}580581/**582* Checks if the specified unit is supported.583* <p>584* This checks if the specified unit can be added to, or subtracted from, this date-time.585* If false, then calling the {@link #plus(long, TemporalUnit)} and586* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.587* <p>588* If the unit is a {@link ChronoUnit} then the query is implemented here.589* The supported units are:590* <ul>591* <li>{@code NANOS}592* <li>{@code MICROS}593* <li>{@code MILLIS}594* <li>{@code SECONDS}595* <li>{@code MINUTES}596* <li>{@code HOURS}597* <li>{@code HALF_DAYS}598* <li>{@code DAYS}599* <li>{@code WEEKS}600* <li>{@code MONTHS}601* <li>{@code YEARS}602* <li>{@code DECADES}603* <li>{@code CENTURIES}604* <li>{@code MILLENNIA}605* <li>{@code ERAS}606* </ul>607* All other {@code ChronoUnit} instances will return false.608* <p>609* If the unit is not a {@code ChronoUnit}, then the result of this method610* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}611* passing {@code this} as the argument.612* Whether the unit is supported is determined by the unit.613*614* @param unit the unit to check, null returns false615* @return true if the unit can be added/subtracted, false if not616*/617@Override // override for Javadoc618public boolean isSupported(TemporalUnit unit) {619return ChronoLocalDateTime.super.isSupported(unit);620}621622//-----------------------------------------------------------------------623/**624* Gets the range of valid values for the specified field.625* <p>626* The range object expresses the minimum and maximum valid values for a field.627* This date-time is used to enhance the accuracy of the returned range.628* If it is not possible to return the range, because the field is not supported629* or for some other reason, an exception is thrown.630* <p>631* If the field is a {@link ChronoField} then the query is implemented here.632* The {@link #isSupported(TemporalField) supported fields} will return633* appropriate range instances.634* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.635* <p>636* If the field is not a {@code ChronoField}, then the result of this method637* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}638* passing {@code this} as the argument.639* Whether the range can be obtained is determined by the field.640*641* @param field the field to query the range for, not null642* @return the range of valid values for the field, not null643* @throws DateTimeException if the range for the field cannot be obtained644* @throws UnsupportedTemporalTypeException if the field is not supported645*/646@Override647public ValueRange range(TemporalField field) {648if (field instanceof ChronoField) {649ChronoField f = (ChronoField) field;650return (f.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 a {@code DateTimeException}.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) {686ChronoField f = (ChronoField) field;687return (f.isTimeBased() ? time.get(field) : date.get(field));688}689return ChronoLocalDateTime.super.get(field);690}691692/**693* Gets the value of the specified field from this date-time as a {@code long}.694* <p>695* This queries this date-time for the value of the specified field.696* If it is not possible to return the value, because the field is not supported697* or for some other reason, an exception is thrown.698* <p>699* If the field is a {@link ChronoField} then the query is implemented here.700* The {@link #isSupported(TemporalField) supported fields} will return valid701* values based on this date-time.702* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.703* <p>704* If the field is not a {@code ChronoField}, then the result of this method705* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}706* passing {@code this} as the argument. Whether the value can be obtained,707* and what the value represents, is determined by the field.708*709* @param field the field to get, not null710* @return the value for the field711* @throws DateTimeException if a value for the field cannot be obtained712* @throws UnsupportedTemporalTypeException if the field is not supported713* @throws ArithmeticException if numeric overflow occurs714*/715@Override716public long getLong(TemporalField field) {717if (field instanceof ChronoField) {718ChronoField f = (ChronoField) field;719return (f.isTimeBased() ? time.getLong(field) : date.getLong(field));720}721return field.getFrom(this);722}723724//-----------------------------------------------------------------------725/**726* Gets the {@code LocalDate} part of this date-time.727* <p>728* This returns a {@code LocalDate} with the same year, month and day729* as this date-time.730*731* @return the date part of this date-time, not null732*/733@Override734public LocalDate toLocalDate() {735return date;736}737738/**739* Gets the year field.740* <p>741* This method returns the primitive {@code int} value for the year.742* <p>743* The year returned by this method is proleptic as per {@code get(YEAR)}.744* To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.745*746* @return the year, from MIN_YEAR to MAX_YEAR747*/748public int getYear() {749return date.getYear();750}751752/**753* Gets the month-of-year field from 1 to 12.754* <p>755* This method returns the month as an {@code int} from 1 to 12.756* Application code is frequently clearer if the enum {@link Month}757* is used by calling {@link #getMonth()}.758*759* @return the month-of-year, from 1 to 12760* @see #getMonth()761*/762public int getMonthValue() {763return date.getMonthValue();764}765766/**767* Gets the month-of-year field using the {@code Month} enum.768* <p>769* This method returns the enum {@link Month} for the month.770* This avoids confusion as to what {@code int} values mean.771* If you need access to the primitive {@code int} value then the enum772* provides the {@link Month#getValue() int value}.773*774* @return the month-of-year, not null775* @see #getMonthValue()776*/777public Month getMonth() {778return date.getMonth();779}780781/**782* Gets the day-of-month field.783* <p>784* This method returns the primitive {@code int} value for the day-of-month.785*786* @return the day-of-month, from 1 to 31787*/788public int getDayOfMonth() {789return date.getDayOfMonth();790}791792/**793* Gets the day-of-year field.794* <p>795* This method returns the primitive {@code int} value for the day-of-year.796*797* @return the day-of-year, from 1 to 365, or 366 in a leap year798*/799public int getDayOfYear() {800return date.getDayOfYear();801}802803/**804* Gets the day-of-week field, which is an enum {@code DayOfWeek}.805* <p>806* This method returns the enum {@link DayOfWeek} for the day-of-week.807* This avoids confusion as to what {@code int} values mean.808* If you need access to the primitive {@code int} value then the enum809* provides the {@link DayOfWeek#getValue() int value}.810* <p>811* Additional information can be obtained from the {@code DayOfWeek}.812* This includes textual names of the values.813*814* @return the day-of-week, not null815*/816public DayOfWeek getDayOfWeek() {817return date.getDayOfWeek();818}819820//-----------------------------------------------------------------------821/**822* Gets the {@code LocalTime} part of this date-time.823* <p>824* This returns a {@code LocalTime} with the same hour, minute, second and825* nanosecond as this date-time.826*827* @return the time part of this date-time, not null828*/829@Override830public LocalTime toLocalTime() {831return time;832}833834/**835* Gets the hour-of-day field.836*837* @return the hour-of-day, from 0 to 23838*/839public int getHour() {840return time.getHour();841}842843/**844* Gets the minute-of-hour field.845*846* @return the minute-of-hour, from 0 to 59847*/848public int getMinute() {849return time.getMinute();850}851852/**853* Gets the second-of-minute field.854*855* @return the second-of-minute, from 0 to 59856*/857public int getSecond() {858return time.getSecond();859}860861/**862* Gets the nano-of-second field.863*864* @return the nano-of-second, from 0 to 999,999,999865*/866public int getNano() {867return time.getNano();868}869870//-----------------------------------------------------------------------871/**872* Returns an adjusted copy of this date-time.873* <p>874* This returns a {@code LocalDateTime}, based on this one, with the date-time adjusted.875* The adjustment takes place using the specified adjuster strategy object.876* Read the documentation of the adjuster to understand what adjustment will be made.877* <p>878* A simple adjuster might simply set the one of the fields, such as the year field.879* A more complex adjuster might set the date to the last day of the month.880* <p>881* A selection of common adjustments is provided in882* {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.883* These include finding the "last day of the month" and "next Wednesday".884* Key date-time classes also implement the {@code TemporalAdjuster} interface,885* such as {@link Month} and {@link java.time.MonthDay MonthDay}.886* The adjuster is responsible for handling special cases, such as the varying887* lengths of month and leap years.888* <p>889* For example this code returns a date on the last day of July:890* <pre>891* import static java.time.Month.*;892* import static java.time.temporal.TemporalAdjusters.*;893*894* result = localDateTime.with(JULY).with(lastDayOfMonth());895* </pre>896* <p>897* The classes {@link LocalDate} and {@link LocalTime} implement {@code TemporalAdjuster},898* thus this method can be used to change the date, time or offset:899* <pre>900* result = localDateTime.with(date);901* result = localDateTime.with(time);902* </pre>903* <p>904* The result of this method is obtained by invoking the905* {@link TemporalAdjuster#adjustInto(Temporal)} method on the906* specified adjuster passing {@code this} as the argument.907* <p>908* This instance is immutable and unaffected by this method call.909*910* @param adjuster the adjuster to use, not null911* @return a {@code LocalDateTime} based on {@code this} with the adjustment made, not null912* @throws DateTimeException if the adjustment cannot be made913* @throws ArithmeticException if numeric overflow occurs914*/915@Override916public LocalDateTime with(TemporalAdjuster adjuster) {917// optimizations918if (adjuster instanceof LocalDate) {919return with((LocalDate) adjuster, time);920} else if (adjuster instanceof LocalTime) {921return with(date, (LocalTime) adjuster);922} else if (adjuster instanceof LocalDateTime) {923return (LocalDateTime) adjuster;924}925return (LocalDateTime) adjuster.adjustInto(this);926}927928/**929* Returns a copy of this date-time with the specified field set to a new value.930* <p>931* This returns a {@code LocalDateTime}, based on this one, with the value932* for the specified field changed.933* This can be used to change any supported field, such as the year, month or day-of-month.934* If it is not possible to set the value, because the field is not supported or for935* some other reason, an exception is thrown.936* <p>937* In some cases, changing the specified field can cause the resulting date-time to become invalid,938* such as changing the month from 31st January to February would make the day-of-month invalid.939* In cases like this, the field is responsible for resolving the date. Typically it will choose940* the previous valid date, which would be the last valid day of February in this example.941* <p>942* If the field is a {@link ChronoField} then the adjustment is implemented here.943* The {@link #isSupported(TemporalField) supported fields} will behave as per944* the matching method on {@link LocalDate#with(TemporalField, long) LocalDate}945* or {@link LocalTime#with(TemporalField, long) LocalTime}.946* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.947* <p>948* If the field is not a {@code ChronoField}, then the result of this method949* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}950* passing {@code this} as the argument. In this case, the field determines951* whether and how to adjust the instant.952* <p>953* This instance is immutable and unaffected by this method call.954*955* @param field the field to set in the result, not null956* @param newValue the new value of the field in the result957* @return a {@code LocalDateTime} based on {@code this} with the specified field set, not null958* @throws DateTimeException if the field cannot be set959* @throws UnsupportedTemporalTypeException if the field is not supported960* @throws ArithmeticException if numeric overflow occurs961*/962@Override963public LocalDateTime with(TemporalField field, long newValue) {964if (field instanceof ChronoField) {965ChronoField f = (ChronoField) field;966if (f.isTimeBased()) {967return with(date, time.with(field, newValue));968} else {969return with(date.with(field, newValue), time);970}971}972return field.adjustInto(this, newValue);973}974975//-----------------------------------------------------------------------976/**977* Returns a copy of this {@code LocalDateTime} with the year altered.978* <p>979* The time does not affect the calculation and will be the same in the result.980* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.981* <p>982* This instance is immutable and unaffected by this method call.983*984* @param year the year to set in the result, from MIN_YEAR to MAX_YEAR985* @return a {@code LocalDateTime} based on this date-time with the requested year, not null986* @throws DateTimeException if the year value is invalid987*/988public LocalDateTime withYear(int year) {989return with(date.withYear(year), time);990}991992/**993* Returns a copy of this {@code LocalDateTime} with the month-of-year altered.994* <p>995* The time does not affect the calculation and will be the same in the result.996* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.997* <p>998* This instance is immutable and unaffected by this method call.999*1000* @param month the month-of-year to set in the result, from 1 (January) to 12 (December)1001* @return a {@code LocalDateTime} based on this date-time with the requested month, not null1002* @throws DateTimeException if the month-of-year value is invalid1003*/1004public LocalDateTime withMonth(int month) {1005return with(date.withMonth(month), time);1006}10071008/**1009* Returns a copy of this {@code LocalDateTime} with the day-of-month altered.1010* <p>1011* If the resulting date-time is invalid, an exception is thrown.1012* The time does not affect the calculation and will be the same in the result.1013* <p>1014* This instance is immutable and unaffected by this method call.1015*1016* @param dayOfMonth the day-of-month to set in the result, from 1 to 28-311017* @return a {@code LocalDateTime} based on this date-time with the requested day, not null1018* @throws DateTimeException if the day-of-month value is invalid,1019* or if the day-of-month is invalid for the month-year1020*/1021public LocalDateTime withDayOfMonth(int dayOfMonth) {1022return with(date.withDayOfMonth(dayOfMonth), time);1023}10241025/**1026* Returns a copy of this {@code LocalDateTime} with the day-of-year altered.1027* <p>1028* If the resulting date-time is invalid, an exception is thrown.1029* <p>1030* This instance is immutable and unaffected by this method call.1031*1032* @param dayOfYear the day-of-year to set in the result, from 1 to 365-3661033* @return a {@code LocalDateTime} based on this date with the requested day, not null1034* @throws DateTimeException if the day-of-year value is invalid,1035* or if the day-of-year is invalid for the year1036*/1037public LocalDateTime withDayOfYear(int dayOfYear) {1038return with(date.withDayOfYear(dayOfYear), time);1039}10401041//-----------------------------------------------------------------------1042/**1043* Returns a copy of this {@code LocalDateTime} with the hour-of-day altered.1044* <p>1045* This instance is immutable and unaffected by this method call.1046*1047* @param hour the hour-of-day to set in the result, from 0 to 231048* @return a {@code LocalDateTime} based on this date-time with the requested hour, not null1049* @throws DateTimeException if the hour value is invalid1050*/1051public LocalDateTime withHour(int hour) {1052LocalTime newTime = time.withHour(hour);1053return with(date, newTime);1054}10551056/**1057* Returns a copy of this {@code LocalDateTime} with the minute-of-hour altered.1058* <p>1059* This instance is immutable and unaffected by this method call.1060*1061* @param minute the minute-of-hour to set in the result, from 0 to 591062* @return a {@code LocalDateTime} based on this date-time with the requested minute, not null1063* @throws DateTimeException if the minute value is invalid1064*/1065public LocalDateTime withMinute(int minute) {1066LocalTime newTime = time.withMinute(minute);1067return with(date, newTime);1068}10691070/**1071* Returns a copy of this {@code LocalDateTime} with the second-of-minute altered.1072* <p>1073* This instance is immutable and unaffected by this method call.1074*1075* @param second the second-of-minute to set in the result, from 0 to 591076* @return a {@code LocalDateTime} based on this date-time with the requested second, not null1077* @throws DateTimeException if the second value is invalid1078*/1079public LocalDateTime withSecond(int second) {1080LocalTime newTime = time.withSecond(second);1081return with(date, newTime);1082}10831084/**1085* Returns a copy of this {@code LocalDateTime} with the nano-of-second altered.1086* <p>1087* This instance is immutable and unaffected by this method call.1088*1089* @param nanoOfSecond the nano-of-second to set in the result, from 0 to 999,999,9991090* @return a {@code LocalDateTime} based on this date-time with the requested nanosecond, not null1091* @throws DateTimeException if the nano value is invalid1092*/1093public LocalDateTime withNano(int nanoOfSecond) {1094LocalTime newTime = time.withNano(nanoOfSecond);1095return with(date, newTime);1096}10971098//-----------------------------------------------------------------------1099/**1100* Returns a copy of this {@code LocalDateTime} with the time truncated.1101* <p>1102* Truncation returns a copy of the original date-time with fields1103* smaller than the specified unit set to zero.1104* For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit1105* will set the second-of-minute and nano-of-second field to zero.1106* <p>1107* The unit must have a {@linkplain TemporalUnit#getDuration() duration}1108* that divides into the length of a standard day without remainder.1109* This includes all supplied time units on {@link ChronoUnit} and1110* {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.1111* <p>1112* This instance is immutable and unaffected by this method call.1113*1114* @param unit the unit to truncate to, not null1115* @return a {@code LocalDateTime} based on this date-time with the time truncated, not null1116* @throws DateTimeException if unable to truncate1117* @throws UnsupportedTemporalTypeException if the unit is not supported1118*/1119public LocalDateTime truncatedTo(TemporalUnit unit) {1120return with(date, time.truncatedTo(unit));1121}11221123//-----------------------------------------------------------------------1124/**1125* Returns a copy of this date-time with the specified amount added.1126* <p>1127* This returns a {@code LocalDateTime}, based on this one, with the specified amount added.1128* The amount is typically {@link Period} or {@link Duration} but may be1129* any other type implementing the {@link TemporalAmount} interface.1130* <p>1131* The calculation is delegated to the amount object by calling1132* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free1133* to implement the addition in any way it wishes, however it typically1134* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation1135* of the amount implementation to determine if it can be successfully added.1136* <p>1137* This instance is immutable and unaffected by this method call.1138*1139* @param amountToAdd the amount to add, not null1140* @return a {@code LocalDateTime} based on this date-time with the addition made, not null1141* @throws DateTimeException if the addition cannot be made1142* @throws ArithmeticException if numeric overflow occurs1143*/1144@Override1145public LocalDateTime plus(TemporalAmount amountToAdd) {1146if (amountToAdd instanceof Period) {1147Period periodToAdd = (Period) amountToAdd;1148return with(date.plus(periodToAdd), time);1149}1150Objects.requireNonNull(amountToAdd, "amountToAdd");1151return (LocalDateTime) amountToAdd.addTo(this);1152}11531154/**1155* Returns a copy of this date-time with the specified amount added.1156* <p>1157* This returns a {@code LocalDateTime}, based on this one, with the amount1158* in terms of the unit added. If it is not possible to add the amount, because the1159* unit is not supported or for some other reason, an exception is thrown.1160* <p>1161* If the field is a {@link ChronoUnit} then the addition is implemented here.1162* Date units are added as per {@link LocalDate#plus(long, TemporalUnit)}.1163* Time units are added as per {@link LocalTime#plus(long, TemporalUnit)} with1164* any overflow in days added equivalent to using {@link #plusDays(long)}.1165* <p>1166* If the field is not a {@code ChronoUnit}, then the result of this method1167* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}1168* passing {@code this} as the argument. In this case, the unit determines1169* whether and how to perform the addition.1170* <p>1171* This instance is immutable and unaffected by this method call.1172*1173* @param amountToAdd the amount of the unit to add to the result, may be negative1174* @param unit the unit of the amount to add, not null1175* @return a {@code LocalDateTime} based on this date-time with the specified amount added, not null1176* @throws DateTimeException if the addition cannot be made1177* @throws UnsupportedTemporalTypeException if the unit is not supported1178* @throws ArithmeticException if numeric overflow occurs1179*/1180@Override1181public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {1182if (unit instanceof ChronoUnit) {1183ChronoUnit f = (ChronoUnit) unit;1184switch (f) {1185case NANOS: return plusNanos(amountToAdd);1186case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);1187case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);1188case SECONDS: return plusSeconds(amountToAdd);1189case MINUTES: return plusMinutes(amountToAdd);1190case HOURS: return plusHours(amountToAdd);1191case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)1192}1193return with(date.plus(amountToAdd, unit), time);1194}1195return unit.addTo(this, amountToAdd);1196}11971198//-----------------------------------------------------------------------1199/**1200* Returns a copy of this {@code LocalDateTime} with the specified number of years added.1201* <p>1202* This method adds the specified amount to the years field in three steps:1203* <ol>1204* <li>Add the input years to the year field</li>1205* <li>Check if the resulting date would be invalid</li>1206* <li>Adjust the day-of-month to the last valid day if necessary</li>1207* </ol>1208* <p>1209* For example, 2008-02-29 (leap year) plus one year would result in the1210* invalid date 2009-02-29 (standard year). Instead of returning an invalid1211* result, the last valid day of the month, 2009-02-28, is selected instead.1212* <p>1213* This instance is immutable and unaffected by this method call.1214*1215* @param years the years to add, may be negative1216* @return a {@code LocalDateTime} based on this date-time with the years added, not null1217* @throws DateTimeException if the result exceeds the supported date range1218*/1219public LocalDateTime plusYears(long years) {1220LocalDate newDate = date.plusYears(years);1221return with(newDate, time);1222}12231224/**1225* Returns a copy of this {@code LocalDateTime} with the specified number of months added.1226* <p>1227* This method adds the specified amount to the months field in three steps:1228* <ol>1229* <li>Add the input months to the month-of-year field</li>1230* <li>Check if the resulting date would be invalid</li>1231* <li>Adjust the day-of-month to the last valid day if necessary</li>1232* </ol>1233* <p>1234* For example, 2007-03-31 plus one month would result in the invalid date1235* 2007-04-31. Instead of returning an invalid result, the last valid day1236* of the month, 2007-04-30, is selected instead.1237* <p>1238* This instance is immutable and unaffected by this method call.1239*1240* @param months the months to add, may be negative1241* @return a {@code LocalDateTime} based on this date-time with the months added, not null1242* @throws DateTimeException if the result exceeds the supported date range1243*/1244public LocalDateTime plusMonths(long months) {1245LocalDate newDate = date.plusMonths(months);1246return with(newDate, time);1247}12481249/**1250* Returns a copy of this {@code LocalDateTime} with the specified number of weeks added.1251* <p>1252* This method adds the specified amount in weeks to the days field incrementing1253* the month and year fields as necessary to ensure the result remains valid.1254* The result is only invalid if the maximum/minimum year is exceeded.1255* <p>1256* For example, 2008-12-31 plus one week would result in 2009-01-07.1257* <p>1258* This instance is immutable and unaffected by this method call.1259*1260* @param weeks the weeks to add, may be negative1261* @return a {@code LocalDateTime} based on this date-time with the weeks added, not null1262* @throws DateTimeException if the result exceeds the supported date range1263*/1264public LocalDateTime plusWeeks(long weeks) {1265LocalDate newDate = date.plusWeeks(weeks);1266return with(newDate, time);1267}12681269/**1270* Returns a copy of this {@code LocalDateTime} with the specified number of days added.1271* <p>1272* This method adds the specified amount to the days field incrementing the1273* month and year fields as necessary to ensure the result remains valid.1274* The result is only invalid if the maximum/minimum year is exceeded.1275* <p>1276* For example, 2008-12-31 plus one day would result in 2009-01-01.1277* <p>1278* This instance is immutable and unaffected by this method call.1279*1280* @param days the days to add, may be negative1281* @return a {@code LocalDateTime} based on this date-time with the days added, not null1282* @throws DateTimeException if the result exceeds the supported date range1283*/1284public LocalDateTime plusDays(long days) {1285LocalDate newDate = date.plusDays(days);1286return with(newDate, time);1287}12881289//-----------------------------------------------------------------------1290/**1291* Returns a copy of this {@code LocalDateTime} with the specified number of hours added.1292* <p>1293* This instance is immutable and unaffected by this method call.1294*1295* @param hours the hours to add, may be negative1296* @return a {@code LocalDateTime} based on this date-time with the hours added, not null1297* @throws DateTimeException if the result exceeds the supported date range1298*/1299public LocalDateTime plusHours(long hours) {1300return plusWithOverflow(date, hours, 0, 0, 0, 1);1301}13021303/**1304* Returns a copy of this {@code LocalDateTime} with the specified number of minutes added.1305* <p>1306* This instance is immutable and unaffected by this method call.1307*1308* @param minutes the minutes to add, may be negative1309* @return a {@code LocalDateTime} based on this date-time with the minutes added, not null1310* @throws DateTimeException if the result exceeds the supported date range1311*/1312public LocalDateTime plusMinutes(long minutes) {1313return plusWithOverflow(date, 0, minutes, 0, 0, 1);1314}13151316/**1317* Returns a copy of this {@code LocalDateTime} with the specified number of seconds added.1318* <p>1319* This instance is immutable and unaffected by this method call.1320*1321* @param seconds the seconds to add, may be negative1322* @return a {@code LocalDateTime} based on this date-time with the seconds added, not null1323* @throws DateTimeException if the result exceeds the supported date range1324*/1325public LocalDateTime plusSeconds(long seconds) {1326return plusWithOverflow(date, 0, 0, seconds, 0, 1);1327}13281329/**1330* Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds added.1331* <p>1332* This instance is immutable and unaffected by this method call.1333*1334* @param nanos the nanos to add, may be negative1335* @return a {@code LocalDateTime} based on this date-time with the nanoseconds added, not null1336* @throws DateTimeException if the result exceeds the supported date range1337*/1338public LocalDateTime plusNanos(long nanos) {1339return plusWithOverflow(date, 0, 0, 0, nanos, 1);1340}13411342//-----------------------------------------------------------------------1343/**1344* Returns a copy of this date-time with the specified amount subtracted.1345* <p>1346* This returns a {@code LocalDateTime}, based on this one, with the specified amount subtracted.1347* The amount is typically {@link Period} or {@link Duration} but may be1348* any other type implementing the {@link TemporalAmount} interface.1349* <p>1350* The calculation is delegated to the amount object by calling1351* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free1352* to implement the subtraction in any way it wishes, however it typically1353* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation1354* of the amount implementation to determine if it can be successfully subtracted.1355* <p>1356* This instance is immutable and unaffected by this method call.1357*1358* @param amountToSubtract the amount to subtract, not null1359* @return a {@code LocalDateTime} based on this date-time with the subtraction made, not null1360* @throws DateTimeException if the subtraction cannot be made1361* @throws ArithmeticException if numeric overflow occurs1362*/1363@Override1364public LocalDateTime minus(TemporalAmount amountToSubtract) {1365if (amountToSubtract instanceof Period) {1366Period periodToSubtract = (Period) amountToSubtract;1367return with(date.minus(periodToSubtract), time);1368}1369Objects.requireNonNull(amountToSubtract, "amountToSubtract");1370return (LocalDateTime) amountToSubtract.subtractFrom(this);1371}13721373/**1374* Returns a copy of this date-time with the specified amount subtracted.1375* <p>1376* This returns a {@code LocalDateTime}, based on this one, with the amount1377* in terms of the unit subtracted. If it is not possible to subtract the amount,1378* because the unit is not supported or for some other reason, an exception is thrown.1379* <p>1380* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.1381* See that method for a full description of how addition, and thus subtraction, works.1382* <p>1383* This instance is immutable and unaffected by this method call.1384*1385* @param amountToSubtract the amount of the unit to subtract from the result, may be negative1386* @param unit the unit of the amount to subtract, not null1387* @return a {@code LocalDateTime} based on this date-time with the specified amount subtracted, not null1388* @throws DateTimeException if the subtraction cannot be made1389* @throws UnsupportedTemporalTypeException if the unit is not supported1390* @throws ArithmeticException if numeric overflow occurs1391*/1392@Override1393public LocalDateTime minus(long amountToSubtract, TemporalUnit unit) {1394return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));1395}13961397//-----------------------------------------------------------------------1398/**1399* Returns a copy of this {@code LocalDateTime} with the specified number of years subtracted.1400* <p>1401* This method subtracts the specified amount from the years field in three steps:1402* <ol>1403* <li>Subtract the input years from the year field</li>1404* <li>Check if the resulting date would be invalid</li>1405* <li>Adjust the day-of-month to the last valid day if necessary</li>1406* </ol>1407* <p>1408* For example, 2008-02-29 (leap year) minus one year would result in the1409* invalid date 2009-02-29 (standard year). Instead of returning an invalid1410* result, the last valid day of the month, 2009-02-28, is selected instead.1411* <p>1412* This instance is immutable and unaffected by this method call.1413*1414* @param years the years to subtract, may be negative1415* @return a {@code LocalDateTime} based on this date-time with the years subtracted, not null1416* @throws DateTimeException if the result exceeds the supported date range1417*/1418public LocalDateTime minusYears(long years) {1419return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));1420}14211422/**1423* Returns a copy of this {@code LocalDateTime} with the specified number of months subtracted.1424* <p>1425* This method subtracts the specified amount from the months field in three steps:1426* <ol>1427* <li>Subtract the input months from the month-of-year field</li>1428* <li>Check if the resulting date would be invalid</li>1429* <li>Adjust the day-of-month to the last valid day if necessary</li>1430* </ol>1431* <p>1432* For example, 2007-03-31 minus one month would result in the invalid date1433* 2007-04-31. Instead of returning an invalid result, the last valid day1434* of the month, 2007-04-30, is selected instead.1435* <p>1436* This instance is immutable and unaffected by this method call.1437*1438* @param months the months to subtract, may be negative1439* @return a {@code LocalDateTime} based on this date-time with the months subtracted, not null1440* @throws DateTimeException if the result exceeds the supported date range1441*/1442public LocalDateTime minusMonths(long months) {1443return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));1444}14451446/**1447* Returns a copy of this {@code LocalDateTime} with the specified number of weeks subtracted.1448* <p>1449* This method subtracts the specified amount in weeks from the days field decrementing1450* the month and year fields as necessary to ensure the result remains valid.1451* The result is only invalid if the maximum/minimum year is exceeded.1452* <p>1453* For example, 2009-01-07 minus one week would result in 2008-12-31.1454* <p>1455* This instance is immutable and unaffected by this method call.1456*1457* @param weeks the weeks to subtract, may be negative1458* @return a {@code LocalDateTime} based on this date-time with the weeks subtracted, not null1459* @throws DateTimeException if the result exceeds the supported date range1460*/1461public LocalDateTime minusWeeks(long weeks) {1462return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));1463}14641465/**1466* Returns a copy of this {@code LocalDateTime} with the specified number of days subtracted.1467* <p>1468* This method subtracts the specified amount from the days field decrementing the1469* month and year fields as necessary to ensure the result remains valid.1470* The result is only invalid if the maximum/minimum year is exceeded.1471* <p>1472* For example, 2009-01-01 minus one day would result in 2008-12-31.1473* <p>1474* This instance is immutable and unaffected by this method call.1475*1476* @param days the days to subtract, may be negative1477* @return a {@code LocalDateTime} based on this date-time with the days subtracted, not null1478* @throws DateTimeException if the result exceeds the supported date range1479*/1480public LocalDateTime minusDays(long days) {1481return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));1482}14831484//-----------------------------------------------------------------------1485/**1486* Returns a copy of this {@code LocalDateTime} with the specified number of hours subtracted.1487* <p>1488* This instance is immutable and unaffected by this method call.1489*1490* @param hours the hours to subtract, may be negative1491* @return a {@code LocalDateTime} based on this date-time with the hours subtracted, not null1492* @throws DateTimeException if the result exceeds the supported date range1493*/1494public LocalDateTime minusHours(long hours) {1495return plusWithOverflow(date, hours, 0, 0, 0, -1);1496}14971498/**1499* Returns a copy of this {@code LocalDateTime} with the specified number of minutes subtracted.1500* <p>1501* This instance is immutable and unaffected by this method call.1502*1503* @param minutes the minutes to subtract, may be negative1504* @return a {@code LocalDateTime} based on this date-time with the minutes subtracted, not null1505* @throws DateTimeException if the result exceeds the supported date range1506*/1507public LocalDateTime minusMinutes(long minutes) {1508return plusWithOverflow(date, 0, minutes, 0, 0, -1);1509}15101511/**1512* Returns a copy of this {@code LocalDateTime} with the specified number of seconds subtracted.1513* <p>1514* This instance is immutable and unaffected by this method call.1515*1516* @param seconds the seconds to subtract, may be negative1517* @return a {@code LocalDateTime} based on this date-time with the seconds subtracted, not null1518* @throws DateTimeException if the result exceeds the supported date range1519*/1520public LocalDateTime minusSeconds(long seconds) {1521return plusWithOverflow(date, 0, 0, seconds, 0, -1);1522}15231524/**1525* Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds subtracted.1526* <p>1527* This instance is immutable and unaffected by this method call.1528*1529* @param nanos the nanos to subtract, may be negative1530* @return a {@code LocalDateTime} based on this date-time with the nanoseconds subtracted, not null1531* @throws DateTimeException if the result exceeds the supported date range1532*/1533public LocalDateTime minusNanos(long nanos) {1534return plusWithOverflow(date, 0, 0, 0, nanos, -1);1535}15361537//-----------------------------------------------------------------------1538/**1539* Returns a copy of this {@code LocalDateTime} with the specified period added.1540* <p>1541* This instance is immutable and unaffected by this method call.1542*1543* @param newDate the new date to base the calculation on, not null1544* @param hours the hours to add, may be negative1545* @param minutes the minutes to add, may be negative1546* @param seconds the seconds to add, may be negative1547* @param nanos the nanos to add, may be negative1548* @param sign the sign to determine add or subtract1549* @return the combined result, not null1550*/1551private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, long nanos, int sign) {1552// 9223372036854775808 long, 2147483648 int1553if ((hours | minutes | seconds | nanos) == 0) {1554return with(newDate, time);1555}1556long totDays = nanos / NANOS_PER_DAY + // max/24*60*60*1B1557seconds / SECONDS_PER_DAY + // max/24*60*601558minutes / MINUTES_PER_DAY + // max/24*601559hours / HOURS_PER_DAY; // max/241560totDays *= sign; // total max*0.4237...1561long totNanos = nanos % NANOS_PER_DAY + // max 864000000000001562(seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND + // max 864000000000001563(minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE + // max 864000000000001564(hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 864000000000001565long curNoD = time.toNanoOfDay(); // max 864000000000001566totNanos = totNanos * sign + curNoD; // total 4320000000000001567totDays += Math.floorDiv(totNanos, NANOS_PER_DAY);1568long newNoD = Math.floorMod(totNanos, NANOS_PER_DAY);1569LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD));1570return with(newDate.plusDays(totDays), newTime);1571}15721573//-----------------------------------------------------------------------1574/**1575* Queries this date-time using the specified query.1576* <p>1577* This queries this date-time using the specified query strategy object.1578* The {@code TemporalQuery} object defines the logic to be used to1579* obtain the result. Read the documentation of the query to understand1580* what the result of this method will be.1581* <p>1582* The result of this method is obtained by invoking the1583* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1584* specified query passing {@code this} as the argument.1585*1586* @param <R> the type of the result1587* @param query the query to invoke, not null1588* @return the query result, null may be returned (defined by the query)1589* @throws DateTimeException if unable to query (defined by the query)1590* @throws ArithmeticException if numeric overflow occurs (defined by the query)1591*/1592@SuppressWarnings("unchecked")1593@Override // override for Javadoc1594public <R> R query(TemporalQuery<R> query) {1595if (query == TemporalQueries.localDate()) {1596return (R) date;1597}1598return ChronoLocalDateTime.super.query(query);1599}16001601/**1602* Adjusts the specified temporal object to have the same date and time as this object.1603* <p>1604* This returns a temporal object of the same observable type as the input1605* with the date and time changed to be the same as this.1606* <p>1607* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1608* twice, passing {@link ChronoField#EPOCH_DAY} and1609* {@link ChronoField#NANO_OF_DAY} as the fields.1610* <p>1611* In most cases, it is clearer to reverse the calling pattern by using1612* {@link Temporal#with(TemporalAdjuster)}:1613* <pre>1614* // these two lines are equivalent, but the second approach is recommended1615* temporal = thisLocalDateTime.adjustInto(temporal);1616* temporal = temporal.with(thisLocalDateTime);1617* </pre>1618* <p>1619* This instance is immutable and unaffected by this method call.1620*1621* @param temporal the target object to be adjusted, not null1622* @return the adjusted object, not null1623* @throws DateTimeException if unable to make the adjustment1624* @throws ArithmeticException if numeric overflow occurs1625*/1626@Override // override for Javadoc1627public Temporal adjustInto(Temporal temporal) {1628return ChronoLocalDateTime.super.adjustInto(temporal);1629}16301631/**1632* Calculates the amount of time until another date-time in terms of the specified unit.1633* <p>1634* This calculates the amount of time between two {@code LocalDateTime}1635* objects in terms of a single {@code TemporalUnit}.1636* The start and end points are {@code this} and the specified date-time.1637* The result will be negative if the end is before the start.1638* The {@code Temporal} passed to this method is converted to a1639* {@code LocalDateTime} using {@link #from(TemporalAccessor)}.1640* For example, the amount in days between two date-times can be calculated1641* using {@code startDateTime.until(endDateTime, DAYS)}.1642* <p>1643* The calculation returns a whole number, representing the number of1644* complete units between the two date-times.1645* For example, the amount in months between 2012-06-15T00:00 and 2012-08-14T23:591646* will only be one month as it is one minute short of two months.1647* <p>1648* There are two equivalent ways of using this method.1649* The first is to invoke this method.1650* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1651* <pre>1652* // these two lines are equivalent1653* amount = start.until(end, MONTHS);1654* amount = MONTHS.between(start, end);1655* </pre>1656* The choice should be made based on which makes the code more readable.1657* <p>1658* The calculation is implemented in this method for {@link ChronoUnit}.1659* The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},1660* {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},1661* {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},1662* {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.1663* Other {@code ChronoUnit} values will throw an exception.1664* <p>1665* If the unit is not a {@code ChronoUnit}, then the result of this method1666* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1667* passing {@code this} as the first argument and the converted input temporal1668* as the second argument.1669* <p>1670* This instance is immutable and unaffected by this method call.1671*1672* @param endExclusive the end date, exclusive, which is converted to a {@code LocalDateTime}, not null1673* @param unit the unit to measure the amount in, not null1674* @return the amount of time between this date-time and the end date-time1675* @throws DateTimeException if the amount cannot be calculated, or the end1676* temporal cannot be converted to a {@code LocalDateTime}1677* @throws UnsupportedTemporalTypeException if the unit is not supported1678* @throws ArithmeticException if numeric overflow occurs1679*/1680@Override1681public long until(Temporal endExclusive, TemporalUnit unit) {1682LocalDateTime end = LocalDateTime.from(endExclusive);1683if (unit instanceof ChronoUnit) {1684if (unit.isTimeBased()) {1685long amount = date.daysUntil(end.date);1686if (amount == 0) {1687return time.until(end.time, unit);1688}1689long timePart = end.time.toNanoOfDay() - time.toNanoOfDay();1690if (amount > 0) {1691amount--; // safe1692timePart += NANOS_PER_DAY; // safe1693} else {1694amount++; // safe1695timePart -= NANOS_PER_DAY; // safe1696}1697switch ((ChronoUnit) unit) {1698case NANOS:1699amount = Math.multiplyExact(amount, NANOS_PER_DAY);1700break;1701case MICROS:1702amount = Math.multiplyExact(amount, MICROS_PER_DAY);1703timePart = timePart / 1000;1704break;1705case MILLIS:1706amount = Math.multiplyExact(amount, MILLIS_PER_DAY);1707timePart = timePart / 1_000_000;1708break;1709case SECONDS:1710amount = Math.multiplyExact(amount, SECONDS_PER_DAY);1711timePart = timePart / NANOS_PER_SECOND;1712break;1713case MINUTES:1714amount = Math.multiplyExact(amount, MINUTES_PER_DAY);1715timePart = timePart / NANOS_PER_MINUTE;1716break;1717case HOURS:1718amount = Math.multiplyExact(amount, HOURS_PER_DAY);1719timePart = timePart / NANOS_PER_HOUR;1720break;1721case HALF_DAYS:1722amount = Math.multiplyExact(amount, 2);1723timePart = timePart / (NANOS_PER_HOUR * 12);1724break;1725}1726return Math.addExact(amount, timePart);1727}1728LocalDate endDate = end.date;1729if (endDate.isAfter(date) && end.time.isBefore(time)) {1730endDate = endDate.minusDays(1);1731} else if (endDate.isBefore(date) && end.time.isAfter(time)) {1732endDate = endDate.plusDays(1);1733}1734return date.until(endDate, unit);1735}1736return unit.between(this, end);1737}17381739/**1740* Formats this date-time using the specified formatter.1741* <p>1742* This date-time will be passed to the formatter to produce a string.1743*1744* @param formatter the formatter to use, not null1745* @return the formatted date-time string, not null1746* @throws DateTimeException if an error occurs during printing1747*/1748@Override // override for Javadoc and performance1749public String format(DateTimeFormatter formatter) {1750Objects.requireNonNull(formatter, "formatter");1751return formatter.format(this);1752}17531754//-----------------------------------------------------------------------1755/**1756* Combines this date-time with an offset to create an {@code OffsetDateTime}.1757* <p>1758* This returns an {@code OffsetDateTime} formed from this date-time at the specified offset.1759* All possible combinations of date-time and offset are valid.1760*1761* @param offset the offset to combine with, not null1762* @return the offset date-time formed from this date-time and the specified offset, not null1763*/1764public OffsetDateTime atOffset(ZoneOffset offset) {1765return OffsetDateTime.of(this, offset);1766}17671768/**1769* Combines this date-time with a time-zone to create a {@code ZonedDateTime}.1770* <p>1771* This returns a {@code ZonedDateTime} formed from this date-time at the1772* specified time-zone. The result will match this date-time as closely as possible.1773* Time-zone rules, such as daylight savings, mean that not every local date-time1774* is valid for the specified zone, thus the local date-time may be adjusted.1775* <p>1776* The local date-time is resolved to a single instant on the time-line.1777* This is achieved by finding a valid offset from UTC/Greenwich for the local1778* date-time as defined by the {@link ZoneRules rules} of the zone ID.1779*<p>1780* In most cases, there is only one valid offset for a local date-time.1781* In the case of an overlap, where clocks are set back, there are two valid offsets.1782* This method uses the earlier offset typically corresponding to "summer".1783* <p>1784* In the case of a gap, where clocks jump forward, there is no valid offset.1785* Instead, the local date-time is adjusted to be later by the length of the gap.1786* For a typical one hour daylight savings change, the local date-time will be1787* moved one hour later into the offset typically corresponding to "summer".1788* <p>1789* To obtain the later offset during an overlap, call1790* {@link ZonedDateTime#withLaterOffsetAtOverlap()} on the result of this method.1791* To throw an exception when there is a gap or overlap, use1792* {@link ZonedDateTime#ofStrict(LocalDateTime, ZoneOffset, ZoneId)}.1793*1794* @param zone the time-zone to use, not null1795* @return the zoned date-time formed from this date-time, not null1796*/1797@Override1798public ZonedDateTime atZone(ZoneId zone) {1799return ZonedDateTime.of(this, zone);1800}18011802//-----------------------------------------------------------------------1803/**1804* Compares this date-time to another date-time.1805* <p>1806* The comparison is primarily based on the date-time, from earliest to latest.1807* It is "consistent with equals", as defined by {@link Comparable}.1808* <p>1809* If all the date-times being compared are instances of {@code LocalDateTime},1810* then the comparison will be entirely based on the date-time.1811* If some dates being compared are in different chronologies, then the1812* chronology is also considered, see {@link ChronoLocalDateTime#compareTo}.1813*1814* @param other the other date-time to compare to, not null1815* @return the comparator value, negative if less, positive if greater1816*/1817@Override // override for Javadoc and performance1818public int compareTo(ChronoLocalDateTime<?> other) {1819if (other instanceof LocalDateTime) {1820return compareTo0((LocalDateTime) other);1821}1822return ChronoLocalDateTime.super.compareTo(other);1823}18241825private int compareTo0(LocalDateTime other) {1826int cmp = date.compareTo0(other.toLocalDate());1827if (cmp == 0) {1828cmp = time.compareTo(other.toLocalTime());1829}1830return cmp;1831}18321833/**1834* Checks if this date-time is after the specified date-time.1835* <p>1836* This checks to see if this date-time represents a point on the1837* local time-line after the other date-time.1838* <pre>1839* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1840* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1841* a.isAfter(b) == false1842* a.isAfter(a) == false1843* b.isAfter(a) == true1844* </pre>1845* <p>1846* This method only considers the position of the two date-times on the local time-line.1847* It does not take into account the chronology, or calendar system.1848* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1849* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1850*1851* @param other the other date-time to compare to, not null1852* @return true if this date-time is after the specified date-time1853*/1854@Override // override for Javadoc and performance1855public boolean isAfter(ChronoLocalDateTime<?> other) {1856if (other instanceof LocalDateTime) {1857return compareTo0((LocalDateTime) other) > 0;1858}1859return ChronoLocalDateTime.super.isAfter(other);1860}18611862/**1863* Checks if this date-time is before the specified date-time.1864* <p>1865* This checks to see if this date-time represents a point on the1866* local time-line before the other date-time.1867* <pre>1868* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1869* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1870* a.isBefore(b) == true1871* a.isBefore(a) == false1872* b.isBefore(a) == false1873* </pre>1874* <p>1875* This method only considers the position of the two date-times on the local time-line.1876* It does not take into account the chronology, or calendar system.1877* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1878* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1879*1880* @param other the other date-time to compare to, not null1881* @return true if this date-time is before the specified date-time1882*/1883@Override // override for Javadoc and performance1884public boolean isBefore(ChronoLocalDateTime<?> other) {1885if (other instanceof LocalDateTime) {1886return compareTo0((LocalDateTime) other) < 0;1887}1888return ChronoLocalDateTime.super.isBefore(other);1889}18901891/**1892* Checks if this date-time is equal to the specified date-time.1893* <p>1894* This checks to see if this date-time represents the same point on the1895* local time-line as the other date-time.1896* <pre>1897* LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);1898* LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);1899* a.isEqual(b) == false1900* a.isEqual(a) == true1901* b.isEqual(a) == false1902* </pre>1903* <p>1904* This method only considers the position of the two date-times on the local time-line.1905* It does not take into account the chronology, or calendar system.1906* This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},1907* but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.1908*1909* @param other the other date-time to compare to, not null1910* @return true if this date-time is equal to the specified date-time1911*/1912@Override // override for Javadoc and performance1913public boolean isEqual(ChronoLocalDateTime<?> other) {1914if (other instanceof LocalDateTime) {1915return compareTo0((LocalDateTime) other) == 0;1916}1917return ChronoLocalDateTime.super.isEqual(other);1918}19191920//-----------------------------------------------------------------------1921/**1922* Checks if this date-time is equal to another date-time.1923* <p>1924* Compares this {@code LocalDateTime} with another ensuring that the date-time is the same.1925* Only objects of type {@code LocalDateTime} are compared, other types return false.1926*1927* @param obj the object to check, null returns false1928* @return true if this is equal to the other date-time1929*/1930@Override1931public boolean equals(Object obj) {1932if (this == obj) {1933return true;1934}1935if (obj instanceof LocalDateTime) {1936LocalDateTime other = (LocalDateTime) obj;1937return date.equals(other.date) && time.equals(other.time);1938}1939return false;1940}19411942/**1943* A hash code for this date-time.1944*1945* @return a suitable hash code1946*/1947@Override1948public int hashCode() {1949return date.hashCode() ^ time.hashCode();1950}19511952//-----------------------------------------------------------------------1953/**1954* Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}.1955* <p>1956* The output will be one of the following ISO-8601 formats:1957* <ul>1958* <li>{@code uuuu-MM-dd'T'HH:mm}</li>1959* <li>{@code uuuu-MM-dd'T'HH:mm:ss}</li>1960* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSS}</li>1961* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSS}</li>1962* <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS}</li>1963* </ul>1964* The format used will be the shortest that outputs the full value of1965* the time where the omitted parts are implied to be zero.1966*1967* @return a string representation of this date-time, not null1968*/1969@Override1970public String toString() {1971return date.toString() + 'T' + time.toString();1972}19731974//-----------------------------------------------------------------------1975/**1976* Writes the object using a1977* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.1978* @serialData1979* <pre>1980* out.writeByte(5); // identifies a LocalDateTime1981* // the <a href="../../serialized-form.html#java.time.LocalDate">date</a> excluding the one byte header1982* // the <a href="../../serialized-form.html#java.time.LocalTime">time</a> excluding the one byte header1983* </pre>1984*1985* @return the instance of {@code Ser}, not null1986*/1987private Object writeReplace() {1988return new Ser(Ser.LOCAL_DATE_TIME_TYPE, this);1989}19901991/**1992* Defend against malicious streams.1993*1994* @param s the stream to read1995* @throws InvalidObjectException always1996*/1997private void readObject(ObjectInputStream s) throws InvalidObjectException {1998throw new InvalidObjectException("Deserialization via serialization delegate");1999}20002001void writeExternal(DataOutput out) throws IOException {2002date.writeExternal(out);2003time.writeExternal(out);2004}20052006static LocalDateTime readExternal(DataInput in) throws IOException {2007LocalDate date = LocalDate.readExternal(in);2008LocalTime time = LocalTime.readExternal(in);2009return LocalDateTime.of(date, time);2010}20112012}201320142015