1 /*
   2  * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time;
  63 
  64 import static java.time.LocalTime.HOURS_PER_DAY;
  65 import static java.time.LocalTime.MICROS_PER_DAY;
  66 import static java.time.LocalTime.MILLIS_PER_DAY;
  67 import static java.time.LocalTime.MINUTES_PER_DAY;
  68 import static java.time.LocalTime.NANOS_PER_DAY;
  69 import static java.time.LocalTime.NANOS_PER_HOUR;
  70 import static java.time.LocalTime.NANOS_PER_MINUTE;
  71 import static java.time.LocalTime.NANOS_PER_SECOND;
  72 import static java.time.LocalTime.SECONDS_PER_DAY;
  73 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  74 
  75 import java.io.DataInput;
  76 import java.io.DataOutput;
  77 import java.io.IOException;
  78 import java.io.InvalidObjectException;
  79 import java.io.ObjectInputStream;
  80 import java.io.Serializable;
  81 import java.time.chrono.ChronoLocalDateTime;
  82 import java.time.format.DateTimeFormatter;
  83 import java.time.format.DateTimeParseException;
  84 import java.time.temporal.ChronoField;
  85 import java.time.temporal.ChronoUnit;
  86 import java.time.temporal.Temporal;
  87 import java.time.temporal.TemporalAccessor;
  88 import java.time.temporal.TemporalAdjuster;
  89 import java.time.temporal.TemporalAmount;
  90 import java.time.temporal.TemporalField;
  91 import java.time.temporal.TemporalQueries;
  92 import java.time.temporal.TemporalQuery;
  93 import java.time.temporal.TemporalUnit;
  94 import java.time.temporal.UnsupportedTemporalTypeException;
  95 import java.time.temporal.ValueRange;
  96 import java.time.zone.ZoneRules;
  97 import java.util.Objects;
  98 
  99 import jdk.internal.util.DateTimeHelper;
 100 
 101 /**
 102  * A date-time without a time-zone in the ISO-8601 calendar system,
 103  * such as {@code 2007-12-03T10:15:30}.
 104  * <p>
 105  * {@code LocalDateTime} is an immutable date-time object that represents a date-time,
 106  * often viewed as year-month-day-hour-minute-second. Other date and time fields,
 107  * such as day-of-year, day-of-week and week-of-year, can also be accessed.
 108  * Time is represented to nanosecond precision.
 109  * For example, the value "2nd October 2007 at 13:45.30.123456789" can be
 110  * stored in a {@code LocalDateTime}.
 111  * <p>
 112  * This class does not store or represent a time-zone.
 113  * Instead, it is a description of the date, as used for birthdays, combined with
 114  * the local time as seen on a wall clock.
 115  * It cannot represent an instant on the time-line without additional information
 116  * such as an offset or time-zone.
 117  * <p>
 118  * The ISO-8601 calendar system is the modern civil calendar system used today
 119  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 120  * system, in which today's rules for leap years are applied for all time.
 121  * For most applications written today, the ISO-8601 rules are entirely suitable.
 122  * However, any application that makes use of historical dates, and requires them
 123  * to be accurate will find the ISO-8601 approach unsuitable.
 124  * <p>
 125  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 126  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
 127  * as interchangeable and should not use instances for synchronization, mutexes, or
 128  * with {@linkplain java.lang.ref.Reference object references}.
 129  *
 130  * <div class="preview-block">
 131  *      <div class="preview-comment">
 132  *          When preview features are enabled, {@code LocalDateTime} is a {@linkplain Class#isValue value class}.
 133  *          Use of value class instances for synchronization, mutexes, or with
 134  *          {@linkplain java.lang.ref.Reference object references} result in
 135  *          {@link IdentityException}.
 136  *      </div>
 137  * </div>
 138  *
 139  * @implSpec
 140  * This class is immutable and thread-safe.
 141  *
 142  * @since 1.8
 143  */
 144 @jdk.internal.ValueBased
 145 @jdk.internal.MigratedValueClass
 146 public final class LocalDateTime
 147         implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {
 148 
 149     /**
 150      * The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'.
 151      * This is the local date-time of midnight at the start of the minimum date.
 152      * This combines {@link LocalDate#MIN} and {@link LocalTime#MIN}.
 153      * This could be used by an application as a "far past" date-time.
 154      */
 155     public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN);
 156     /**
 157      * The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'.
 158      * This is the local date-time just before midnight at the end of the maximum date.
 159      * This combines {@link LocalDate#MAX} and {@link LocalTime#MAX}.
 160      * This could be used by an application as a "far future" date-time.
 161      */
 162     public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX);
 163 
 164     /**
 165      * Serialization version.
 166      */
 167     @java.io.Serial
 168     private static final long serialVersionUID = 6207766400415563566L;
 169 
 170     /**
 171      * @serial The date part.
 172      */
 173     private final LocalDate date;
 174     /**
 175      * @serial The time part.
 176      */
 177     private final LocalTime time;
 178 
 179     //-----------------------------------------------------------------------
 180     /**
 181      * Obtains the current date-time from the system clock in the default time-zone.
 182      * <p>
 183      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 184      * time-zone to obtain the current date-time.
 185      * <p>
 186      * Using this method will prevent the ability to use an alternate clock for testing
 187      * because the clock is hard-coded.
 188      *
 189      * @return the current date-time using the system clock and default time-zone, not null
 190      */
 191     public static LocalDateTime now() {
 192         return now(Clock.systemDefaultZone());
 193     }
 194 
 195     /**
 196      * Obtains the current date-time from the system clock in the specified time-zone.
 197      * <p>
 198      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date-time.
 199      * Specifying the time-zone avoids dependence on the default time-zone.
 200      * <p>
 201      * Using this method will prevent the ability to use an alternate clock for testing
 202      * because the clock is hard-coded.
 203      *
 204      * @param zone  the zone ID to use, not null
 205      * @return the current date-time using the system clock, not null
 206      */
 207     public static LocalDateTime now(ZoneId zone) {
 208         return now(Clock.system(zone));
 209     }
 210 
 211     /**
 212      * Obtains the current date-time from the specified clock.
 213      * <p>
 214      * This will query the specified clock to obtain the current date-time.
 215      * Using this method allows the use of an alternate clock for testing.
 216      * The alternate clock may be introduced using {@link Clock dependency injection}.
 217      *
 218      * @param clock  the clock to use, not null
 219      * @return the current date-time, not null
 220      */
 221     public static LocalDateTime now(Clock clock) {
 222         Objects.requireNonNull(clock, "clock");
 223         final Instant now = clock.instant();  // called once
 224         ZoneOffset offset = clock.getZone().getRules().getOffset(now);
 225         return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);
 226     }
 227 
 228     //-----------------------------------------------------------------------
 229     /**
 230      * Obtains an instance of {@code LocalDateTime} from year, month,
 231      * day, hour and minute, setting the second and nanosecond to zero.
 232      * <p>
 233      * This returns a {@code LocalDateTime} with the specified year, month,
 234      * day-of-month, hour and minute.
 235      * The day must be valid for the year and month, otherwise an exception will be thrown.
 236      * The second and nanosecond fields will be set to zero.
 237      *
 238      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 239      * @param month  the month-of-year to represent, not null
 240      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 241      * @param hour  the hour-of-day to represent, from 0 to 23
 242      * @param minute  the minute-of-hour to represent, from 0 to 59
 243      * @return the local date-time, not null
 244      * @throws DateTimeException if the value of any field is out of range,
 245      *  or if the day-of-month is invalid for the month-year
 246      */
 247     public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {
 248         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 249         LocalTime time = LocalTime.of(hour, minute);
 250         return new LocalDateTime(date, time);
 251     }
 252 
 253     /**
 254      * Obtains an instance of {@code LocalDateTime} from year, month,
 255      * day, hour, minute and second, setting the nanosecond to zero.
 256      * <p>
 257      * This returns a {@code LocalDateTime} with the specified year, month,
 258      * day-of-month, hour, minute and second.
 259      * The day must be valid for the year and month, otherwise an exception will be thrown.
 260      * The nanosecond field will be set to zero.
 261      *
 262      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 263      * @param month  the month-of-year to represent, not null
 264      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 265      * @param hour  the hour-of-day to represent, from 0 to 23
 266      * @param minute  the minute-of-hour to represent, from 0 to 59
 267      * @param second  the second-of-minute to represent, from 0 to 59
 268      * @return the local date-time, not null
 269      * @throws DateTimeException if the value of any field is out of range,
 270      *  or if the day-of-month is invalid for the month-year
 271      */
 272     public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) {
 273         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 274         LocalTime time = LocalTime.of(hour, minute, second);
 275         return new LocalDateTime(date, time);
 276     }
 277 
 278     /**
 279      * Obtains an instance of {@code LocalDateTime} from year, month,
 280      * day, hour, minute, second and nanosecond.
 281      * <p>
 282      * This returns a {@code LocalDateTime} with the specified year, month,
 283      * day-of-month, hour, minute, second and nanosecond.
 284      * The day must be valid for the year and month, otherwise an exception will be thrown.
 285      *
 286      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 287      * @param month  the month-of-year to represent, not null
 288      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 289      * @param hour  the hour-of-day to represent, from 0 to 23
 290      * @param minute  the minute-of-hour to represent, from 0 to 59
 291      * @param second  the second-of-minute to represent, from 0 to 59
 292      * @param nanoOfSecond  the nano-of-second to represent, from 0 to 999,999,999
 293      * @return the local date-time, not null
 294      * @throws DateTimeException if the value of any field is out of range,
 295      *  or if the day-of-month is invalid for the month-year
 296      */
 297     public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {
 298         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 299         LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);
 300         return new LocalDateTime(date, time);
 301     }
 302 
 303     //-----------------------------------------------------------------------
 304     /**
 305      * Obtains an instance of {@code LocalDateTime} from year, month,
 306      * day, hour and minute, setting the second and nanosecond to zero.
 307      * <p>
 308      * This returns a {@code LocalDateTime} with the specified year, month,
 309      * day-of-month, hour and minute.
 310      * The day must be valid for the year and month, otherwise an exception will be thrown.
 311      * The second and nanosecond fields will be set to zero.
 312      *
 313      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 314      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 315      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 316      * @param hour  the hour-of-day to represent, from 0 to 23
 317      * @param minute  the minute-of-hour to represent, from 0 to 59
 318      * @return the local date-time, not null
 319      * @throws DateTimeException if the value of any field is out of range,
 320      *  or if the day-of-month is invalid for the month-year
 321      */
 322     public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) {
 323         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 324         LocalTime time = LocalTime.of(hour, minute);
 325         return new LocalDateTime(date, time);
 326     }
 327 
 328     /**
 329      * Obtains an instance of {@code LocalDateTime} from year, month,
 330      * day, hour, minute and second, setting the nanosecond to zero.
 331      * <p>
 332      * This returns a {@code LocalDateTime} with the specified year, month,
 333      * day-of-month, hour, minute and second.
 334      * The day must be valid for the year and month, otherwise an exception will be thrown.
 335      * The nanosecond field will be set to zero.
 336      *
 337      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 338      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 339      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 340      * @param hour  the hour-of-day to represent, from 0 to 23
 341      * @param minute  the minute-of-hour to represent, from 0 to 59
 342      * @param second  the second-of-minute to represent, from 0 to 59
 343      * @return the local date-time, not null
 344      * @throws DateTimeException if the value of any field is out of range,
 345      *  or if the day-of-month is invalid for the month-year
 346      */
 347     public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) {
 348         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 349         LocalTime time = LocalTime.of(hour, minute, second);
 350         return new LocalDateTime(date, time);
 351     }
 352 
 353     /**
 354      * Obtains an instance of {@code LocalDateTime} from year, month,
 355      * day, hour, minute, second and nanosecond.
 356      * <p>
 357      * This returns a {@code LocalDateTime} with the specified year, month,
 358      * day-of-month, hour, minute, second and nanosecond.
 359      * The day must be valid for the year and month, otherwise an exception will be thrown.
 360      *
 361      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 362      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 363      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 364      * @param hour  the hour-of-day to represent, from 0 to 23
 365      * @param minute  the minute-of-hour to represent, from 0 to 59
 366      * @param second  the second-of-minute to represent, from 0 to 59
 367      * @param nanoOfSecond  the nano-of-second to represent, from 0 to 999,999,999
 368      * @return the local date-time, not null
 369      * @throws DateTimeException if the value of any field is out of range,
 370      *  or if the day-of-month is invalid for the month-year
 371      */
 372     public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {
 373         LocalDate date = LocalDate.of(year, month, dayOfMonth);
 374         LocalTime time = LocalTime.of(hour, minute, second, nanoOfSecond);
 375         return new LocalDateTime(date, time);
 376     }
 377 
 378     /**
 379      * Obtains an instance of {@code LocalDateTime} from a date and time.
 380      *
 381      * @param date  the local date, not null
 382      * @param time  the local time, not null
 383      * @return the local date-time, not null
 384      */
 385     public static LocalDateTime of(LocalDate date, LocalTime time) {
 386         Objects.requireNonNull(date, "date");
 387         Objects.requireNonNull(time, "time");
 388         return new LocalDateTime(date, time);
 389     }
 390 
 391     //-------------------------------------------------------------------------
 392     /**
 393      * Obtains an instance of {@code LocalDateTime} from an {@code Instant} and zone ID.
 394      * <p>
 395      * This creates a local date-time based on the specified instant.
 396      * First, the offset from UTC/Greenwich is obtained using the zone ID and instant,
 397      * which is simple as there is only one valid offset for each instant.
 398      * Then, the instant and offset are used to calculate the local date-time.
 399      *
 400      * @param instant  the instant to create the date-time from, not null
 401      * @param zone  the time-zone, which may be an offset, not null
 402      * @return the local date-time, not null
 403      * @throws DateTimeException if the result exceeds the supported range
 404      */
 405     public static LocalDateTime ofInstant(Instant instant, ZoneId zone) {
 406         Objects.requireNonNull(instant, "instant");
 407         Objects.requireNonNull(zone, "zone");
 408         ZoneRules rules = zone.getRules();
 409         ZoneOffset offset = rules.getOffset(instant);
 410         return ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
 411     }
 412 
 413     /**
 414      * Obtains an instance of {@code LocalDateTime} using seconds from the
 415      * epoch of 1970-01-01T00:00:00Z.
 416      * <p>
 417      * This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field
 418      * to be converted to a local date-time. This is primarily intended for
 419      * low-level conversions rather than general application usage.
 420      *
 421      * @param epochSecond  the number of seconds from the epoch of 1970-01-01T00:00:00Z
 422      * @param nanoOfSecond  the nanosecond within the second, from 0 to 999,999,999
 423      * @param offset  the zone offset, not null
 424      * @return the local date-time, not null
 425      * @throws DateTimeException if the result exceeds the supported range,
 426      *  or if the nano-of-second is invalid
 427      */
 428     public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {
 429         Objects.requireNonNull(offset, "offset");
 430         NANO_OF_SECOND.checkValidValue(nanoOfSecond);
 431         long localSecond = epochSecond + offset.getTotalSeconds();  // overflow caught later
 432         long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);
 433         int secsOfDay = Math.floorMod(localSecond, SECONDS_PER_DAY);
 434         LocalDate date = LocalDate.ofEpochDay(localEpochDay);
 435         LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + nanoOfSecond);
 436         return new LocalDateTime(date, time);
 437     }
 438 
 439     //-----------------------------------------------------------------------
 440     /**
 441      * Obtains an instance of {@code LocalDateTime} from a temporal object.
 442      * <p>
 443      * This obtains a local date-time based on the specified temporal.
 444      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 445      * which this factory converts to an instance of {@code LocalDateTime}.
 446      * <p>
 447      * The conversion extracts and combines the {@code LocalDate} and the
 448      * {@code LocalTime} from the temporal object.
 449      * Implementations are permitted to perform optimizations such as accessing
 450      * those fields that are equivalent to the relevant objects.
 451      * <p>
 452      * This method matches the signature of the functional interface {@link TemporalQuery}
 453      * allowing it to be used as a query via method reference, {@code LocalDateTime::from}.
 454      *
 455      * @param temporal  the temporal object to convert, not null
 456      * @return the local date-time, not null
 457      * @throws DateTimeException if unable to convert to a {@code LocalDateTime}
 458      */
 459     public static LocalDateTime from(TemporalAccessor temporal) {
 460         if (temporal instanceof LocalDateTime) {
 461             return (LocalDateTime) temporal;
 462         } else if (temporal instanceof ZonedDateTime) {
 463             return ((ZonedDateTime) temporal).toLocalDateTime();
 464         } else if (temporal instanceof OffsetDateTime) {
 465             return ((OffsetDateTime) temporal).toLocalDateTime();
 466         }
 467         try {
 468             LocalDate date = LocalDate.from(temporal);
 469             LocalTime time = LocalTime.from(temporal);
 470             return new LocalDateTime(date, time);
 471         } catch (DateTimeException ex) {
 472             throw new DateTimeException("Unable to obtain LocalDateTime from TemporalAccessor: " +
 473                     temporal + " of type " + temporal.getClass().getName(), ex);
 474         }
 475     }
 476 
 477     //-----------------------------------------------------------------------
 478     /**
 479      * Obtains an instance of {@code LocalDateTime} from a text string such as {@code 2007-12-03T10:15:30}.
 480      * <p>
 481      * The string must represent a valid date-time and is parsed using
 482      * {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE_TIME}.
 483      *
 484      * @param text  the text to parse such as "2007-12-03T10:15:30", not null
 485      * @return the parsed local date-time, not null
 486      * @throws DateTimeParseException if the text cannot be parsed
 487      */
 488     public static LocalDateTime parse(CharSequence text) {
 489         return parse(text, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
 490     }
 491 
 492     /**
 493      * Obtains an instance of {@code LocalDateTime} from a text string using a specific formatter.
 494      * <p>
 495      * The text is parsed using the formatter, returning a date-time.
 496      *
 497      * @param text  the text to parse, not null
 498      * @param formatter  the formatter to use, not null
 499      * @return the parsed local date-time, not null
 500      * @throws DateTimeParseException if the text cannot be parsed
 501      */
 502     public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {
 503         Objects.requireNonNull(formatter, "formatter");
 504         return formatter.parse(text, LocalDateTime::from);
 505     }
 506 
 507     //-----------------------------------------------------------------------
 508     /**
 509      * Constructor.
 510      *
 511      * @param date  the date part of the date-time, validated not null
 512      * @param time  the time part of the date-time, validated not null
 513      */
 514     private LocalDateTime(LocalDate date, LocalTime time) {
 515         this.date = date;
 516         this.time = time;
 517     }
 518 
 519     /**
 520      * Returns a copy of this date-time with the new date and time, checking
 521      * to see if a new object is in fact required.
 522      *
 523      * @param newDate  the date of the new date-time, not null
 524      * @param newTime  the time of the new date-time, not null
 525      * @return the date-time, not null
 526      */
 527     private LocalDateTime with(LocalDate newDate, LocalTime newTime) {
 528         if (date == newDate && time == newTime) {
 529             return this;
 530         }
 531         return new LocalDateTime(newDate, newTime);
 532     }
 533 
 534     //-----------------------------------------------------------------------
 535     /**
 536      * Checks if the specified field is supported.
 537      * <p>
 538      * This checks if this date-time can be queried for the specified field.
 539      * If false, then calling the {@link #range(TemporalField) range},
 540      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
 541      * methods will throw an exception.
 542      * <p>
 543      * If the field is a {@link ChronoField} then the query is implemented here.
 544      * The supported fields are:
 545      * <ul>
 546      * <li>{@code NANO_OF_SECOND}
 547      * <li>{@code NANO_OF_DAY}
 548      * <li>{@code MICRO_OF_SECOND}
 549      * <li>{@code MICRO_OF_DAY}
 550      * <li>{@code MILLI_OF_SECOND}
 551      * <li>{@code MILLI_OF_DAY}
 552      * <li>{@code SECOND_OF_MINUTE}
 553      * <li>{@code SECOND_OF_DAY}
 554      * <li>{@code MINUTE_OF_HOUR}
 555      * <li>{@code MINUTE_OF_DAY}
 556      * <li>{@code HOUR_OF_AMPM}
 557      * <li>{@code CLOCK_HOUR_OF_AMPM}
 558      * <li>{@code HOUR_OF_DAY}
 559      * <li>{@code CLOCK_HOUR_OF_DAY}
 560      * <li>{@code AMPM_OF_DAY}
 561      * <li>{@code DAY_OF_WEEK}
 562      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}
 563      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}
 564      * <li>{@code DAY_OF_MONTH}
 565      * <li>{@code DAY_OF_YEAR}
 566      * <li>{@code EPOCH_DAY}
 567      * <li>{@code ALIGNED_WEEK_OF_MONTH}
 568      * <li>{@code ALIGNED_WEEK_OF_YEAR}
 569      * <li>{@code MONTH_OF_YEAR}
 570      * <li>{@code PROLEPTIC_MONTH}
 571      * <li>{@code YEAR_OF_ERA}
 572      * <li>{@code YEAR}
 573      * <li>{@code ERA}
 574      * </ul>
 575      * All other {@code ChronoField} instances will return false.
 576      * <p>
 577      * If the field is not a {@code ChronoField}, then the result of this method
 578      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 579      * passing {@code this} as the argument.
 580      * Whether the field is supported is determined by the field.
 581      *
 582      * @param field  the field to check, null returns false
 583      * @return true if the field is supported on this date-time, false if not
 584      */
 585     @Override
 586     public boolean isSupported(TemporalField field) {
 587         if (field instanceof ChronoField chronoField) {
 588             return chronoField.isDateBased() || chronoField.isTimeBased();
 589         }
 590         return field != null && field.isSupportedBy(this);
 591     }
 592 
 593     /**
 594      * Checks if the specified unit is supported.
 595      * <p>
 596      * This checks if the specified unit can be added to, or subtracted from, this date-time.
 597      * If false, then calling the {@link #plus(long, TemporalUnit)} and
 598      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
 599      * <p>
 600      * If the unit is a {@link ChronoUnit} then the query is implemented here.
 601      * The supported units are:
 602      * <ul>
 603      * <li>{@code NANOS}
 604      * <li>{@code MICROS}
 605      * <li>{@code MILLIS}
 606      * <li>{@code SECONDS}
 607      * <li>{@code MINUTES}
 608      * <li>{@code HOURS}
 609      * <li>{@code HALF_DAYS}
 610      * <li>{@code DAYS}
 611      * <li>{@code WEEKS}
 612      * <li>{@code MONTHS}
 613      * <li>{@code YEARS}
 614      * <li>{@code DECADES}
 615      * <li>{@code CENTURIES}
 616      * <li>{@code MILLENNIA}
 617      * <li>{@code ERAS}
 618      * </ul>
 619      * All other {@code ChronoUnit} instances will return false.
 620      * <p>
 621      * If the unit is not a {@code ChronoUnit}, then the result of this method
 622      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
 623      * passing {@code this} as the argument.
 624      * Whether the unit is supported is determined by the unit.
 625      *
 626      * @param unit  the unit to check, null returns false
 627      * @return true if the unit can be added/subtracted, false if not
 628      */
 629     @Override  // override for Javadoc
 630     public boolean isSupported(TemporalUnit unit) {
 631         return ChronoLocalDateTime.super.isSupported(unit);
 632     }
 633 
 634     //-----------------------------------------------------------------------
 635     /**
 636      * Gets the range of valid values for the specified field.
 637      * <p>
 638      * The range object expresses the minimum and maximum valid values for a field.
 639      * This date-time is used to enhance the accuracy of the returned range.
 640      * If it is not possible to return the range, because the field is not supported
 641      * or for some other reason, an exception is thrown.
 642      * <p>
 643      * If the field is a {@link ChronoField} then the query is implemented here.
 644      * The {@link #isSupported(TemporalField) supported fields} will return
 645      * appropriate range instances.
 646      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 647      * <p>
 648      * If the field is not a {@code ChronoField}, then the result of this method
 649      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 650      * passing {@code this} as the argument.
 651      * Whether the range can be obtained is determined by the field.
 652      *
 653      * @param field  the field to query the range for, not null
 654      * @return the range of valid values for the field, not null
 655      * @throws DateTimeException if the range for the field cannot be obtained
 656      * @throws UnsupportedTemporalTypeException if the field is not supported
 657      */
 658     @Override
 659     public ValueRange range(TemporalField field) {
 660         if (field instanceof ChronoField chronoField) {
 661             return (chronoField.isTimeBased() ? time.range(field) : date.range(field));
 662         }
 663         return field.rangeRefinedBy(this);
 664     }
 665 
 666     /**
 667      * Gets the value of the specified field from this date-time as an {@code int}.
 668      * <p>
 669      * This queries this date-time for the value of the specified field.
 670      * The returned value will always be within the valid range of values for the field.
 671      * If it is not possible to return the value, because the field is not supported
 672      * or for some other reason, an exception is thrown.
 673      * <p>
 674      * If the field is a {@link ChronoField} then the query is implemented here.
 675      * The {@link #isSupported(TemporalField) supported fields} will return valid
 676      * values based on this date-time, except {@code NANO_OF_DAY}, {@code MICRO_OF_DAY},
 677      * {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH} which are too large to fit in
 678      * an {@code int} and throw an {@code UnsupportedTemporalTypeException}.
 679      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 680      * <p>
 681      * If the field is not a {@code ChronoField}, then the result of this method
 682      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 683      * passing {@code this} as the argument. Whether the value can be obtained,
 684      * and what the value represents, is determined by the field.
 685      *
 686      * @param field  the field to get, not null
 687      * @return the value for the field
 688      * @throws DateTimeException if a value for the field cannot be obtained or
 689      *         the value is outside the range of valid values for the field
 690      * @throws UnsupportedTemporalTypeException if the field is not supported or
 691      *         the range of values exceeds an {@code int}
 692      * @throws ArithmeticException if numeric overflow occurs
 693      */
 694     @Override
 695     public int get(TemporalField field) {
 696         if (field instanceof ChronoField chronoField) {
 697             return (chronoField.isTimeBased() ? time.get(field) : date.get(field));
 698         }
 699         return ChronoLocalDateTime.super.get(field);
 700     }
 701 
 702     /**
 703      * Gets the value of the specified field from this date-time as a {@code long}.
 704      * <p>
 705      * This queries this date-time for the value of the specified field.
 706      * If it is not possible to return the value, because the field is not supported
 707      * or for some other reason, an exception is thrown.
 708      * <p>
 709      * If the field is a {@link ChronoField} then the query is implemented here.
 710      * The {@link #isSupported(TemporalField) supported fields} will return valid
 711      * values based on this date-time.
 712      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 713      * <p>
 714      * If the field is not a {@code ChronoField}, then the result of this method
 715      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 716      * passing {@code this} as the argument. Whether the value can be obtained,
 717      * and what the value represents, is determined by the field.
 718      *
 719      * @param field  the field to get, not null
 720      * @return the value for the field
 721      * @throws DateTimeException if a value for the field cannot be obtained
 722      * @throws UnsupportedTemporalTypeException if the field is not supported
 723      * @throws ArithmeticException if numeric overflow occurs
 724      */
 725     @Override
 726     public long getLong(TemporalField field) {
 727         if (field instanceof ChronoField chronoField) {
 728             return (chronoField.isTimeBased() ? time.getLong(field) : date.getLong(field));
 729         }
 730         return field.getFrom(this);
 731     }
 732 
 733     //-----------------------------------------------------------------------
 734     /**
 735      * Gets the {@code LocalDate} part of this date-time.
 736      * <p>
 737      * This returns a {@code LocalDate} with the same year, month and day
 738      * as this date-time.
 739      *
 740      * @return the date part of this date-time, not null
 741      */
 742     @Override
 743     public LocalDate toLocalDate() {
 744         return date;
 745     }
 746 
 747     /**
 748      * Gets the year field.
 749      * <p>
 750      * This method returns the primitive {@code int} value for the year.
 751      * <p>
 752      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 753      * To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.
 754      *
 755      * @return the year, from MIN_YEAR to MAX_YEAR
 756      */
 757     public int getYear() {
 758         return date.getYear();
 759     }
 760 
 761     /**
 762      * Gets the month-of-year field from 1 to 12.
 763      * <p>
 764      * This method returns the month as an {@code int} from 1 to 12.
 765      * Application code is frequently clearer if the enum {@link Month}
 766      * is used by calling {@link #getMonth()}.
 767      *
 768      * @return the month-of-year, from 1 to 12
 769      * @see #getMonth()
 770      */
 771     public int getMonthValue() {
 772         return date.getMonthValue();
 773     }
 774 
 775     /**
 776      * Gets the month-of-year field using the {@code Month} enum.
 777      * <p>
 778      * This method returns the enum {@link Month} for the month.
 779      * This avoids confusion as to what {@code int} values mean.
 780      * If you need access to the primitive {@code int} value then the enum
 781      * provides the {@link Month#getValue() int value}.
 782      *
 783      * @return the month-of-year, not null
 784      * @see #getMonthValue()
 785      */
 786     public Month getMonth() {
 787         return date.getMonth();
 788     }
 789 
 790     /**
 791      * Gets the day-of-month field.
 792      * <p>
 793      * This method returns the primitive {@code int} value for the day-of-month.
 794      *
 795      * @return the day-of-month, from 1 to 31
 796      */
 797     public int getDayOfMonth() {
 798         return date.getDayOfMonth();
 799     }
 800 
 801     /**
 802      * Gets the day-of-year field.
 803      * <p>
 804      * This method returns the primitive {@code int} value for the day-of-year.
 805      *
 806      * @return the day-of-year, from 1 to 365, or 366 in a leap year
 807      */
 808     public int getDayOfYear() {
 809         return date.getDayOfYear();
 810     }
 811 
 812     /**
 813      * Gets the day-of-week field, which is an enum {@code DayOfWeek}.
 814      * <p>
 815      * This method returns the enum {@link DayOfWeek} for the day-of-week.
 816      * This avoids confusion as to what {@code int} values mean.
 817      * If you need access to the primitive {@code int} value then the enum
 818      * provides the {@link DayOfWeek#getValue() int value}.
 819      * <p>
 820      * Additional information can be obtained from the {@code DayOfWeek}.
 821      * This includes textual names of the values.
 822      *
 823      * @return the day-of-week, not null
 824      */
 825     public DayOfWeek getDayOfWeek() {
 826         return date.getDayOfWeek();
 827     }
 828 
 829     //-----------------------------------------------------------------------
 830     /**
 831      * Gets the {@code LocalTime} part of this date-time.
 832      * <p>
 833      * This returns a {@code LocalTime} with the same hour, minute, second and
 834      * nanosecond as this date-time.
 835      *
 836      * @return the time part of this date-time, not null
 837      */
 838     @Override
 839     public LocalTime toLocalTime() {
 840         return time;
 841     }
 842 
 843     /**
 844      * Gets the hour-of-day field.
 845      *
 846      * @return the hour-of-day, from 0 to 23
 847      */
 848     public int getHour() {
 849         return time.getHour();
 850     }
 851 
 852     /**
 853      * Gets the minute-of-hour field.
 854      *
 855      * @return the minute-of-hour, from 0 to 59
 856      */
 857     public int getMinute() {
 858         return time.getMinute();
 859     }
 860 
 861     /**
 862      * Gets the second-of-minute field.
 863      *
 864      * @return the second-of-minute, from 0 to 59
 865      */
 866     public int getSecond() {
 867         return time.getSecond();
 868     }
 869 
 870     /**
 871      * Gets the nano-of-second field.
 872      *
 873      * @return the nano-of-second, from 0 to 999,999,999
 874      */
 875     public int getNano() {
 876         return time.getNano();
 877     }
 878 
 879     //-----------------------------------------------------------------------
 880     /**
 881      * Returns an adjusted copy of this date-time.
 882      * <p>
 883      * This returns a {@code LocalDateTime}, based on this one, with the date-time adjusted.
 884      * The adjustment takes place using the specified adjuster strategy object.
 885      * Read the documentation of the adjuster to understand what adjustment will be made.
 886      * <p>
 887      * A simple adjuster might simply set the one of the fields, such as the year field.
 888      * A more complex adjuster might set the date to the last day of the month.
 889      * <p>
 890      * A selection of common adjustments is provided in
 891      * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
 892      * These include finding the "last day of the month" and "next Wednesday".
 893      * Key date-time classes also implement the {@code TemporalAdjuster} interface,
 894      * such as {@link Month} and {@link java.time.MonthDay MonthDay}.
 895      * The adjuster is responsible for handling special cases, such as the varying
 896      * lengths of month and leap years.
 897      * <p>
 898      * For example this code returns a date on the last day of July:
 899      * <pre>
 900      *  import static java.time.Month.*;
 901      *  import static java.time.temporal.TemporalAdjusters.*;
 902      *
 903      *  result = localDateTime.with(JULY).with(lastDayOfMonth());
 904      * </pre>
 905      * <p>
 906      * The classes {@link LocalDate} and {@link LocalTime} implement {@code TemporalAdjuster},
 907      * thus this method can be used to change the date, time or offset:
 908      * <pre>
 909      *  result = localDateTime.with(date);
 910      *  result = localDateTime.with(time);
 911      * </pre>
 912      * <p>
 913      * The result of this method is obtained by invoking the
 914      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 915      * specified adjuster passing {@code this} as the argument.
 916      * <p>
 917      * This instance is immutable and unaffected by this method call.
 918      *
 919      * @param adjuster the adjuster to use, not null
 920      * @return a {@code LocalDateTime} based on {@code this} with the adjustment made, not null
 921      * @throws DateTimeException if the adjustment cannot be made
 922      * @throws ArithmeticException if numeric overflow occurs
 923      */
 924     @Override
 925     public LocalDateTime with(TemporalAdjuster adjuster) {
 926         // optimizations
 927         if (adjuster instanceof LocalDate) {
 928             return with((LocalDate) adjuster, time);
 929         } else if (adjuster instanceof LocalTime) {
 930             return with(date, (LocalTime) adjuster);
 931         } else if (adjuster instanceof LocalDateTime) {
 932             return (LocalDateTime) adjuster;
 933         }
 934         return (LocalDateTime) adjuster.adjustInto(this);
 935     }
 936 
 937     /**
 938      * Returns a copy of this date-time with the specified field set to a new value.
 939      * <p>
 940      * This returns a {@code LocalDateTime}, based on this one, with the value
 941      * for the specified field changed.
 942      * This can be used to change any supported field, such as the year, month or day-of-month.
 943      * If it is not possible to set the value, because the field is not supported or for
 944      * some other reason, an exception is thrown.
 945      * <p>
 946      * In some cases, changing the specified field can cause the resulting date-time to become invalid,
 947      * such as changing the month from 31st January to February would make the day-of-month invalid.
 948      * In cases like this, the field is responsible for resolving the date. Typically it will choose
 949      * the previous valid date, which would be the last valid day of February in this example.
 950      * <p>
 951      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 952      * The {@link #isSupported(TemporalField) supported fields} will behave as per
 953      * the matching method on {@link LocalDate#with(TemporalField, long) LocalDate}
 954      * or {@link LocalTime#with(TemporalField, long) LocalTime}.
 955      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 956      * <p>
 957      * If the field is not a {@code ChronoField}, then the result of this method
 958      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 959      * passing {@code this} as the argument. In this case, the field determines
 960      * whether and how to adjust the instant.
 961      * <p>
 962      * This instance is immutable and unaffected by this method call.
 963      *
 964      * @param field  the field to set in the result, not null
 965      * @param newValue  the new value of the field in the result
 966      * @return a {@code LocalDateTime} based on {@code this} with the specified field set, not null
 967      * @throws DateTimeException if the field cannot be set
 968      * @throws UnsupportedTemporalTypeException if the field is not supported
 969      * @throws ArithmeticException if numeric overflow occurs
 970      */
 971     @Override
 972     public LocalDateTime with(TemporalField field, long newValue) {
 973         if (field instanceof ChronoField chronoField) {
 974             if (chronoField.isTimeBased()) {
 975                 return with(date, time.with(field, newValue));
 976             } else {
 977                 return with(date.with(field, newValue), time);
 978             }
 979         }
 980         return field.adjustInto(this, newValue);
 981     }
 982 
 983     //-----------------------------------------------------------------------
 984     /**
 985      * Returns a copy of this {@code LocalDateTime} with the year altered.
 986      * <p>
 987      * The time does not affect the calculation and will be the same in the result.
 988      * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
 989      * <p>
 990      * This instance is immutable and unaffected by this method call.
 991      *
 992      * @param year  the year to set in the result, from MIN_YEAR to MAX_YEAR
 993      * @return a {@code LocalDateTime} based on this date-time with the requested year, not null
 994      * @throws DateTimeException if the year value is invalid
 995      */
 996     public LocalDateTime withYear(int year) {
 997         return with(date.withYear(year), time);
 998     }
 999 
1000     /**
1001      * Returns a copy of this {@code LocalDateTime} with the month-of-year altered.
1002      * <p>
1003      * The time does not affect the calculation and will be the same in the result.
1004      * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
1005      * <p>
1006      * This instance is immutable and unaffected by this method call.
1007      *
1008      * @param month  the month-of-year to set in the result, from 1 (January) to 12 (December)
1009      * @return a {@code LocalDateTime} based on this date-time with the requested month, not null
1010      * @throws DateTimeException if the month-of-year value is invalid
1011      */
1012     public LocalDateTime withMonth(int month) {
1013         return with(date.withMonth(month), time);
1014     }
1015 
1016     /**
1017      * Returns a copy of this {@code LocalDateTime} with the day-of-month altered.
1018      * <p>
1019      * If the resulting date-time is invalid, an exception is thrown.
1020      * The time does not affect the calculation and will be the same in the result.
1021      * <p>
1022      * This instance is immutable and unaffected by this method call.
1023      *
1024      * @param dayOfMonth  the day-of-month to set in the result, from 1 to 28-31
1025      * @return a {@code LocalDateTime} based on this date-time with the requested day, not null
1026      * @throws DateTimeException if the day-of-month value is invalid,
1027      *  or if the day-of-month is invalid for the month-year
1028      */
1029     public LocalDateTime withDayOfMonth(int dayOfMonth) {
1030         return with(date.withDayOfMonth(dayOfMonth), time);
1031     }
1032 
1033     /**
1034      * Returns a copy of this {@code LocalDateTime} with the day-of-year altered.
1035      * <p>
1036      * If the resulting date-time is invalid, an exception is thrown.
1037      * <p>
1038      * This instance is immutable and unaffected by this method call.
1039      *
1040      * @param dayOfYear  the day-of-year to set in the result, from 1 to 365-366
1041      * @return a {@code LocalDateTime} based on this date with the requested day, not null
1042      * @throws DateTimeException if the day-of-year value is invalid,
1043      *  or if the day-of-year is invalid for the year
1044      */
1045     public LocalDateTime withDayOfYear(int dayOfYear) {
1046         return with(date.withDayOfYear(dayOfYear), time);
1047     }
1048 
1049     //-----------------------------------------------------------------------
1050     /**
1051      * Returns a copy of this {@code LocalDateTime} with the hour-of-day altered.
1052      * <p>
1053      * This instance is immutable and unaffected by this method call.
1054      *
1055      * @param hour  the hour-of-day to set in the result, from 0 to 23
1056      * @return a {@code LocalDateTime} based on this date-time with the requested hour, not null
1057      * @throws DateTimeException if the hour value is invalid
1058      */
1059     public LocalDateTime withHour(int hour) {
1060         LocalTime newTime = time.withHour(hour);
1061         return with(date, newTime);
1062     }
1063 
1064     /**
1065      * Returns a copy of this {@code LocalDateTime} with the minute-of-hour altered.
1066      * <p>
1067      * This instance is immutable and unaffected by this method call.
1068      *
1069      * @param minute  the minute-of-hour to set in the result, from 0 to 59
1070      * @return a {@code LocalDateTime} based on this date-time with the requested minute, not null
1071      * @throws DateTimeException if the minute value is invalid
1072      */
1073     public LocalDateTime withMinute(int minute) {
1074         LocalTime newTime = time.withMinute(minute);
1075         return with(date, newTime);
1076     }
1077 
1078     /**
1079      * Returns a copy of this {@code LocalDateTime} with the second-of-minute altered.
1080      * <p>
1081      * This instance is immutable and unaffected by this method call.
1082      *
1083      * @param second  the second-of-minute to set in the result, from 0 to 59
1084      * @return a {@code LocalDateTime} based on this date-time with the requested second, not null
1085      * @throws DateTimeException if the second value is invalid
1086      */
1087     public LocalDateTime withSecond(int second) {
1088         LocalTime newTime = time.withSecond(second);
1089         return with(date, newTime);
1090     }
1091 
1092     /**
1093      * Returns a copy of this {@code LocalDateTime} with the nano-of-second altered.
1094      * <p>
1095      * This instance is immutable and unaffected by this method call.
1096      *
1097      * @param nanoOfSecond  the nano-of-second to set in the result, from 0 to 999,999,999
1098      * @return a {@code LocalDateTime} based on this date-time with the requested nanosecond, not null
1099      * @throws DateTimeException if the nano value is invalid
1100      */
1101     public LocalDateTime withNano(int nanoOfSecond) {
1102         LocalTime newTime = time.withNano(nanoOfSecond);
1103         return with(date, newTime);
1104     }
1105 
1106     //-----------------------------------------------------------------------
1107     /**
1108      * Returns a copy of this {@code LocalDateTime} with the time truncated.
1109      * <p>
1110      * Truncation returns a copy of the original date-time with fields
1111      * smaller than the specified unit set to zero.
1112      * For example, truncating with the {@link ChronoUnit#MINUTES minutes} unit
1113      * will set the second-of-minute and nano-of-second field to zero.
1114      * <p>
1115      * The unit must have a {@linkplain TemporalUnit#getDuration() duration}
1116      * that divides into the length of a standard day without remainder.
1117      * This includes all supplied time units on {@link ChronoUnit} and
1118      * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception.
1119      * <p>
1120      * This instance is immutable and unaffected by this method call.
1121      *
1122      * @param unit  the unit to truncate to, not null
1123      * @return a {@code LocalDateTime} based on this date-time with the time truncated, not null
1124      * @throws DateTimeException if unable to truncate
1125      * @throws UnsupportedTemporalTypeException if the unit is not supported
1126      */
1127     public LocalDateTime truncatedTo(TemporalUnit unit) {
1128         return with(date, time.truncatedTo(unit));
1129     }
1130 
1131     //-----------------------------------------------------------------------
1132     /**
1133      * Returns a copy of this date-time with the specified amount added.
1134      * <p>
1135      * This returns a {@code LocalDateTime}, based on this one, with the specified amount added.
1136      * The amount is typically {@link Period} or {@link Duration} but may be
1137      * any other type implementing the {@link TemporalAmount} interface.
1138      * <p>
1139      * The calculation is delegated to the amount object by calling
1140      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
1141      * to implement the addition in any way it wishes, however it typically
1142      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
1143      * of the amount implementation to determine if it can be successfully added.
1144      * <p>
1145      * This instance is immutable and unaffected by this method call.
1146      *
1147      * @param amountToAdd  the amount to add, not null
1148      * @return a {@code LocalDateTime} based on this date-time with the addition made, not null
1149      * @throws DateTimeException if the addition cannot be made
1150      * @throws ArithmeticException if numeric overflow occurs
1151      */
1152     @Override
1153     public LocalDateTime plus(TemporalAmount amountToAdd) {
1154         if (amountToAdd instanceof Period periodToAdd) {
1155             return with(date.plus(periodToAdd), time);
1156         }
1157         Objects.requireNonNull(amountToAdd, "amountToAdd");
1158         return (LocalDateTime) amountToAdd.addTo(this);
1159     }
1160 
1161     /**
1162      * Returns a copy of this date-time with the specified amount added.
1163      * <p>
1164      * This returns a {@code LocalDateTime}, based on this one, with the amount
1165      * in terms of the unit added. If it is not possible to add the amount, because the
1166      * unit is not supported or for some other reason, an exception is thrown.
1167      * <p>
1168      * If the field is a {@link ChronoUnit} then the addition is implemented here.
1169      * Date units are added as per {@link LocalDate#plus(long, TemporalUnit)}.
1170      * Time units are added as per {@link LocalTime#plus(long, TemporalUnit)} with
1171      * any overflow in days added equivalent to using {@link #plusDays(long)}.
1172      * <p>
1173      * If the field is not a {@code ChronoUnit}, then the result of this method
1174      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
1175      * passing {@code this} as the argument. In this case, the unit determines
1176      * whether and how to perform the addition.
1177      * <p>
1178      * This instance is immutable and unaffected by this method call.
1179      *
1180      * @param amountToAdd  the amount of the unit to add to the result, may be negative
1181      * @param unit  the unit of the amount to add, not null
1182      * @return a {@code LocalDateTime} based on this date-time with the specified amount added, not null
1183      * @throws DateTimeException if the addition cannot be made
1184      * @throws UnsupportedTemporalTypeException if the unit is not supported
1185      * @throws ArithmeticException if numeric overflow occurs
1186      */
1187     @Override
1188     public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {
1189         if (unit instanceof ChronoUnit chronoUnit) {
1190             return switch (chronoUnit) {
1191                 case NANOS     -> plusNanos(amountToAdd);
1192                 case MICROS    -> plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
1193                 case MILLIS    -> plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);
1194                 case SECONDS   -> plusSeconds(amountToAdd);
1195                 case MINUTES   -> plusMinutes(amountToAdd);
1196                 case HOURS     -> plusHours(amountToAdd);
1197                 case HALF_DAYS -> plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)
1198                 default -> with(date.plus(amountToAdd, unit), time);
1199             };
1200         }
1201         return unit.addTo(this, amountToAdd);
1202     }
1203 
1204     //-----------------------------------------------------------------------
1205     /**
1206      * Returns a copy of this {@code LocalDateTime} with the specified number of years added.
1207      * <p>
1208      * This method adds the specified amount to the years field in three steps:
1209      * <ol>
1210      * <li>Add the input years to the year field</li>
1211      * <li>Check if the resulting date would be invalid</li>
1212      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1213      * </ol>
1214      * <p>
1215      * For example, 2008-02-29 (leap year) plus one year would result in the
1216      * invalid date 2009-02-29 (standard year). Instead of returning an invalid
1217      * result, the last valid day of the month, 2009-02-28, is selected instead.
1218      * <p>
1219      * This instance is immutable and unaffected by this method call.
1220      *
1221      * @param years  the years to add, may be negative
1222      * @return a {@code LocalDateTime} based on this date-time with the years added, not null
1223      * @throws DateTimeException if the result exceeds the supported date range
1224      */
1225     public LocalDateTime plusYears(long years) {
1226         LocalDate newDate = date.plusYears(years);
1227         return with(newDate, time);
1228     }
1229 
1230     /**
1231      * Returns a copy of this {@code LocalDateTime} with the specified number of months added.
1232      * <p>
1233      * This method adds the specified amount to the months field in three steps:
1234      * <ol>
1235      * <li>Add the input months to the month-of-year field</li>
1236      * <li>Check if the resulting date would be invalid</li>
1237      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1238      * </ol>
1239      * <p>
1240      * For example, 2007-03-31 plus one month would result in the invalid date
1241      * 2007-04-31. Instead of returning an invalid result, the last valid day
1242      * of the month, 2007-04-30, is selected instead.
1243      * <p>
1244      * This instance is immutable and unaffected by this method call.
1245      *
1246      * @param months  the months to add, may be negative
1247      * @return a {@code LocalDateTime} based on this date-time with the months added, not null
1248      * @throws DateTimeException if the result exceeds the supported date range
1249      */
1250     public LocalDateTime plusMonths(long months) {
1251         LocalDate newDate = date.plusMonths(months);
1252         return with(newDate, time);
1253     }
1254 
1255     /**
1256      * Returns a copy of this {@code LocalDateTime} with the specified number of weeks added.
1257      * <p>
1258      * This method adds the specified amount in weeks to the days field incrementing
1259      * the month and year fields as necessary to ensure the result remains valid.
1260      * The result is only invalid if the maximum/minimum year is exceeded.
1261      * <p>
1262      * For example, 2008-12-31 plus one week would result in 2009-01-07.
1263      * <p>
1264      * This instance is immutable and unaffected by this method call.
1265      *
1266      * @param weeks  the weeks to add, may be negative
1267      * @return a {@code LocalDateTime} based on this date-time with the weeks added, not null
1268      * @throws DateTimeException if the result exceeds the supported date range
1269      */
1270     public LocalDateTime plusWeeks(long weeks) {
1271         LocalDate newDate = date.plusWeeks(weeks);
1272         return with(newDate, time);
1273     }
1274 
1275     /**
1276      * Returns a copy of this {@code LocalDateTime} with the specified number of days added.
1277      * <p>
1278      * This method adds the specified amount to the days field incrementing the
1279      * month and year fields as necessary to ensure the result remains valid.
1280      * The result is only invalid if the maximum/minimum year is exceeded.
1281      * <p>
1282      * For example, 2008-12-31 plus one day would result in 2009-01-01.
1283      * <p>
1284      * This instance is immutable and unaffected by this method call.
1285      *
1286      * @param days  the days to add, may be negative
1287      * @return a {@code LocalDateTime} based on this date-time with the days added, not null
1288      * @throws DateTimeException if the result exceeds the supported date range
1289      */
1290     public LocalDateTime plusDays(long days) {
1291         LocalDate newDate = date.plusDays(days);
1292         return with(newDate, time);
1293     }
1294 
1295     //-----------------------------------------------------------------------
1296     /**
1297      * Returns a copy of this {@code LocalDateTime} with the specified number of hours added.
1298      * <p>
1299      * This instance is immutable and unaffected by this method call.
1300      *
1301      * @param hours  the hours to add, may be negative
1302      * @return a {@code LocalDateTime} based on this date-time with the hours added, not null
1303      * @throws DateTimeException if the result exceeds the supported date range
1304      */
1305     public LocalDateTime plusHours(long hours) {
1306         return plusWithOverflow(date, hours, 0, 0, 0, 1);
1307     }
1308 
1309     /**
1310      * Returns a copy of this {@code LocalDateTime} with the specified number of minutes added.
1311      * <p>
1312      * This instance is immutable and unaffected by this method call.
1313      *
1314      * @param minutes  the minutes to add, may be negative
1315      * @return a {@code LocalDateTime} based on this date-time with the minutes added, not null
1316      * @throws DateTimeException if the result exceeds the supported date range
1317      */
1318     public LocalDateTime plusMinutes(long minutes) {
1319         return plusWithOverflow(date, 0, minutes, 0, 0, 1);
1320     }
1321 
1322     /**
1323      * Returns a copy of this {@code LocalDateTime} with the specified number of seconds added.
1324      * <p>
1325      * This instance is immutable and unaffected by this method call.
1326      *
1327      * @param seconds  the seconds to add, may be negative
1328      * @return a {@code LocalDateTime} based on this date-time with the seconds added, not null
1329      * @throws DateTimeException if the result exceeds the supported date range
1330      */
1331     public LocalDateTime plusSeconds(long seconds) {
1332         return plusWithOverflow(date, 0, 0, seconds, 0, 1);
1333     }
1334 
1335     /**
1336      * Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds added.
1337      * <p>
1338      * This instance is immutable and unaffected by this method call.
1339      *
1340      * @param nanos  the nanos to add, may be negative
1341      * @return a {@code LocalDateTime} based on this date-time with the nanoseconds added, not null
1342      * @throws DateTimeException if the result exceeds the supported date range
1343      */
1344     public LocalDateTime plusNanos(long nanos) {
1345         return plusWithOverflow(date, 0, 0, 0, nanos, 1);
1346     }
1347 
1348     //-----------------------------------------------------------------------
1349     /**
1350      * Returns a copy of this date-time with the specified amount subtracted.
1351      * <p>
1352      * This returns a {@code LocalDateTime}, based on this one, with the specified amount subtracted.
1353      * The amount is typically {@link Period} or {@link Duration} but may be
1354      * any other type implementing the {@link TemporalAmount} interface.
1355      * <p>
1356      * The calculation is delegated to the amount object by calling
1357      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
1358      * to implement the subtraction in any way it wishes, however it typically
1359      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
1360      * of the amount implementation to determine if it can be successfully subtracted.
1361      * <p>
1362      * This instance is immutable and unaffected by this method call.
1363      *
1364      * @param amountToSubtract  the amount to subtract, not null
1365      * @return a {@code LocalDateTime} based on this date-time with the subtraction made, not null
1366      * @throws DateTimeException if the subtraction cannot be made
1367      * @throws ArithmeticException if numeric overflow occurs
1368      */
1369     @Override
1370     public LocalDateTime minus(TemporalAmount amountToSubtract) {
1371         if (amountToSubtract instanceof Period periodToSubtract) {
1372             return with(date.minus(periodToSubtract), time);
1373         }
1374         Objects.requireNonNull(amountToSubtract, "amountToSubtract");
1375         return (LocalDateTime) amountToSubtract.subtractFrom(this);
1376     }
1377 
1378     /**
1379      * Returns a copy of this date-time with the specified amount subtracted.
1380      * <p>
1381      * This returns a {@code LocalDateTime}, based on this one, with the amount
1382      * in terms of the unit subtracted. If it is not possible to subtract the amount,
1383      * because the unit is not supported or for some other reason, an exception is thrown.
1384      * <p>
1385      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
1386      * See that method for a full description of how addition, and thus subtraction, works.
1387      * <p>
1388      * This instance is immutable and unaffected by this method call.
1389      *
1390      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
1391      * @param unit  the unit of the amount to subtract, not null
1392      * @return a {@code LocalDateTime} based on this date-time with the specified amount subtracted, not null
1393      * @throws DateTimeException if the subtraction cannot be made
1394      * @throws UnsupportedTemporalTypeException if the unit is not supported
1395      * @throws ArithmeticException if numeric overflow occurs
1396      */
1397     @Override
1398     public LocalDateTime minus(long amountToSubtract, TemporalUnit unit) {
1399         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
1400     }
1401 
1402     //-----------------------------------------------------------------------
1403     /**
1404      * Returns a copy of this {@code LocalDateTime} with the specified number of years subtracted.
1405      * <p>
1406      * This method subtracts the specified amount from the years field in three steps:
1407      * <ol>
1408      * <li>Subtract the input years from the year field</li>
1409      * <li>Check if the resulting date would be invalid</li>
1410      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1411      * </ol>
1412      * <p>
1413      * For example, 2008-02-29 (leap year) minus one year would result in the
1414      * invalid date 2007-02-29 (standard year). Instead of returning an invalid
1415      * result, the last valid day of the month, 2007-02-28, is selected instead.
1416      * <p>
1417      * This instance is immutable and unaffected by this method call.
1418      *
1419      * @param years  the years to subtract, may be negative
1420      * @return a {@code LocalDateTime} based on this date-time with the years subtracted, not null
1421      * @throws DateTimeException if the result exceeds the supported date range
1422      */
1423     public LocalDateTime minusYears(long years) {
1424         return (years == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-years));
1425     }
1426 
1427     /**
1428      * Returns a copy of this {@code LocalDateTime} with the specified number of months subtracted.
1429      * <p>
1430      * This method subtracts the specified amount from the months field in three steps:
1431      * <ol>
1432      * <li>Subtract the input months from the month-of-year field</li>
1433      * <li>Check if the resulting date would be invalid</li>
1434      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1435      * </ol>
1436      * <p>
1437      * For example, 2007-03-31 minus one month would result in the invalid date
1438      * 2007-02-31. Instead of returning an invalid result, the last valid day
1439      * of the month, 2007-02-28, is selected instead.
1440      * <p>
1441      * This instance is immutable and unaffected by this method call.
1442      *
1443      * @param months  the months to subtract, may be negative
1444      * @return a {@code LocalDateTime} based on this date-time with the months subtracted, not null
1445      * @throws DateTimeException if the result exceeds the supported date range
1446      */
1447     public LocalDateTime minusMonths(long months) {
1448         return (months == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-months));
1449     }
1450 
1451     /**
1452      * Returns a copy of this {@code LocalDateTime} with the specified number of weeks subtracted.
1453      * <p>
1454      * This method subtracts the specified amount in weeks from the days field decrementing
1455      * the month and year fields as necessary to ensure the result remains valid.
1456      * The result is only invalid if the maximum/minimum year is exceeded.
1457      * <p>
1458      * For example, 2009-01-07 minus one week would result in 2008-12-31.
1459      * <p>
1460      * This instance is immutable and unaffected by this method call.
1461      *
1462      * @param weeks  the weeks to subtract, may be negative
1463      * @return a {@code LocalDateTime} based on this date-time with the weeks subtracted, not null
1464      * @throws DateTimeException if the result exceeds the supported date range
1465      */
1466     public LocalDateTime minusWeeks(long weeks) {
1467         return (weeks == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeks));
1468     }
1469 
1470     /**
1471      * Returns a copy of this {@code LocalDateTime} with the specified number of days subtracted.
1472      * <p>
1473      * This method subtracts the specified amount from the days field decrementing the
1474      * month and year fields as necessary to ensure the result remains valid.
1475      * The result is only invalid if the maximum/minimum year is exceeded.
1476      * <p>
1477      * For example, 2009-01-01 minus one day would result in 2008-12-31.
1478      * <p>
1479      * This instance is immutable and unaffected by this method call.
1480      *
1481      * @param days  the days to subtract, may be negative
1482      * @return a {@code LocalDateTime} based on this date-time with the days subtracted, not null
1483      * @throws DateTimeException if the result exceeds the supported date range
1484      */
1485     public LocalDateTime minusDays(long days) {
1486         return (days == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-days));
1487     }
1488 
1489     //-----------------------------------------------------------------------
1490     /**
1491      * Returns a copy of this {@code LocalDateTime} with the specified number of hours subtracted.
1492      * <p>
1493      * This instance is immutable and unaffected by this method call.
1494      *
1495      * @param hours  the hours to subtract, may be negative
1496      * @return a {@code LocalDateTime} based on this date-time with the hours subtracted, not null
1497      * @throws DateTimeException if the result exceeds the supported date range
1498      */
1499     public LocalDateTime minusHours(long hours) {
1500         return plusWithOverflow(date, hours, 0, 0, 0, -1);
1501    }
1502 
1503     /**
1504      * Returns a copy of this {@code LocalDateTime} with the specified number of minutes subtracted.
1505      * <p>
1506      * This instance is immutable and unaffected by this method call.
1507      *
1508      * @param minutes  the minutes to subtract, may be negative
1509      * @return a {@code LocalDateTime} based on this date-time with the minutes subtracted, not null
1510      * @throws DateTimeException if the result exceeds the supported date range
1511      */
1512     public LocalDateTime minusMinutes(long minutes) {
1513         return plusWithOverflow(date, 0, minutes, 0, 0, -1);
1514     }
1515 
1516     /**
1517      * Returns a copy of this {@code LocalDateTime} with the specified number of seconds subtracted.
1518      * <p>
1519      * This instance is immutable and unaffected by this method call.
1520      *
1521      * @param seconds  the seconds to subtract, may be negative
1522      * @return a {@code LocalDateTime} based on this date-time with the seconds subtracted, not null
1523      * @throws DateTimeException if the result exceeds the supported date range
1524      */
1525     public LocalDateTime minusSeconds(long seconds) {
1526         return plusWithOverflow(date, 0, 0, seconds, 0, -1);
1527     }
1528 
1529     /**
1530      * Returns a copy of this {@code LocalDateTime} with the specified number of nanoseconds subtracted.
1531      * <p>
1532      * This instance is immutable and unaffected by this method call.
1533      *
1534      * @param nanos  the nanos to subtract, may be negative
1535      * @return a {@code LocalDateTime} based on this date-time with the nanoseconds subtracted, not null
1536      * @throws DateTimeException if the result exceeds the supported date range
1537      */
1538     public LocalDateTime minusNanos(long nanos) {
1539         return plusWithOverflow(date, 0, 0, 0, nanos, -1);
1540     }
1541 
1542     //-----------------------------------------------------------------------
1543     /**
1544      * Returns a copy of this {@code LocalDateTime} with the specified period added.
1545      * <p>
1546      * This instance is immutable and unaffected by this method call.
1547      *
1548      * @param newDate  the new date to base the calculation on, not null
1549      * @param hours  the hours to add, may be negative
1550      * @param minutes the minutes to add, may be negative
1551      * @param seconds the seconds to add, may be negative
1552      * @param nanos the nanos to add, may be negative
1553      * @param sign  the sign to determine add or subtract
1554      * @return the combined result, not null
1555      */
1556     private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, long nanos, int sign) {
1557         // 9223372036854775808 long, 2147483648 int
1558         if ((hours | minutes | seconds | nanos) == 0) {
1559             return with(newDate, time);
1560         }
1561         long totDays = nanos / NANOS_PER_DAY +             //   max/24*60*60*1B
1562                 seconds / SECONDS_PER_DAY +                //   max/24*60*60
1563                 minutes / MINUTES_PER_DAY +                //   max/24*60
1564                 hours / HOURS_PER_DAY;                     //   max/24
1565         totDays *= sign;                                   // total max*0.4237...
1566         long totNanos = nanos % NANOS_PER_DAY +                    //   max  86400000000000
1567                 (seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND +   //   max  86400000000000
1568                 (minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE +   //   max  86400000000000
1569                 (hours % HOURS_PER_DAY) * NANOS_PER_HOUR;          //   max  86400000000000
1570         long curNoD = time.toNanoOfDay();                       //   max  86400000000000
1571         totNanos = totNanos * sign + curNoD;                    // total 432000000000000
1572         totDays += Math.floorDiv(totNanos, NANOS_PER_DAY);
1573         long newNoD = Math.floorMod(totNanos, NANOS_PER_DAY);
1574         LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD));
1575         return with(newDate.plusDays(totDays), newTime);
1576     }
1577 
1578     //-----------------------------------------------------------------------
1579     /**
1580      * Queries this date-time using the specified query.
1581      * <p>
1582      * This queries this date-time using the specified query strategy object.
1583      * The {@code TemporalQuery} object defines the logic to be used to
1584      * obtain the result. Read the documentation of the query to understand
1585      * what the result of this method will be.
1586      * <p>
1587      * The result of this method is obtained by invoking the
1588      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1589      * specified query passing {@code this} as the argument.
1590      *
1591      * @param <R> the type of the result
1592      * @param query  the query to invoke, not null
1593      * @return the query result, null may be returned (defined by the query)
1594      * @throws DateTimeException if unable to query (defined by the query)
1595      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1596      */
1597     @SuppressWarnings("unchecked")
1598     @Override  // override for Javadoc
1599     public <R> R query(TemporalQuery<R> query) {
1600         if (query == TemporalQueries.localDate()) {
1601             return (R) date;
1602         }
1603         return ChronoLocalDateTime.super.query(query);
1604     }
1605 
1606     /**
1607      * Adjusts the specified temporal object to have the same date and time as this object.
1608      * <p>
1609      * This returns a temporal object of the same observable type as the input
1610      * with the date and time changed to be the same as this.
1611      * <p>
1612      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
1613      * twice, passing {@link ChronoField#EPOCH_DAY} and
1614      * {@link ChronoField#NANO_OF_DAY} as the fields.
1615      * <p>
1616      * In most cases, it is clearer to reverse the calling pattern by using
1617      * {@link Temporal#with(TemporalAdjuster)}:
1618      * <pre>
1619      *   // these two lines are equivalent, but the second approach is recommended
1620      *   temporal = thisLocalDateTime.adjustInto(temporal);
1621      *   temporal = temporal.with(thisLocalDateTime);
1622      * </pre>
1623      * <p>
1624      * This instance is immutable and unaffected by this method call.
1625      *
1626      * @param temporal  the target object to be adjusted, not null
1627      * @return the adjusted object, not null
1628      * @throws DateTimeException if unable to make the adjustment
1629      * @throws ArithmeticException if numeric overflow occurs
1630      */
1631     @Override  // override for Javadoc
1632     public Temporal adjustInto(Temporal temporal) {
1633         return ChronoLocalDateTime.super.adjustInto(temporal);
1634     }
1635 
1636     /**
1637      * Calculates the amount of time until another date-time in terms of the specified unit.
1638      * <p>
1639      * This calculates the amount of time between two {@code LocalDateTime}
1640      * objects in terms of a single {@code TemporalUnit}.
1641      * The start and end points are {@code this} and the specified date-time.
1642      * The result will be negative if the end is before the start.
1643      * The {@code Temporal} passed to this method is converted to a
1644      * {@code LocalDateTime} using {@link #from(TemporalAccessor)}.
1645      * For example, the amount in days between two date-times can be calculated
1646      * using {@code startDateTime.until(endDateTime, DAYS)}.
1647      * <p>
1648      * The calculation returns a whole number, representing the number of
1649      * complete units between the two date-times.
1650      * For example, the amount in months between 2012-06-15T00:00 and 2012-08-14T23:59
1651      * will only be one month as it is one minute short of two months.
1652      * <p>
1653      * There are two equivalent ways of using this method.
1654      * The first is to invoke this method.
1655      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1656      * <pre>
1657      *   // these two lines are equivalent
1658      *   amount = start.until(end, MONTHS);
1659      *   amount = MONTHS.between(start, end);
1660      * </pre>
1661      * The choice should be made based on which makes the code more readable.
1662      * <p>
1663      * The calculation is implemented in this method for {@link ChronoUnit}.
1664      * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
1665      * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},
1666      * {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},
1667      * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
1668      * Other {@code ChronoUnit} values will throw an exception.
1669      * <p>
1670      * If the unit is not a {@code ChronoUnit}, then the result of this method
1671      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1672      * passing {@code this} as the first argument and the converted input temporal
1673      * as the second argument.
1674      * <p>
1675      * This instance is immutable and unaffected by this method call.
1676      *
1677      * @param endExclusive  the end date, exclusive, which is converted to a {@code LocalDateTime}, not null
1678      * @param unit  the unit to measure the amount in, not null
1679      * @return the amount of time between this date-time and the end date-time
1680      * @throws DateTimeException if the amount cannot be calculated, or the end
1681      *  temporal cannot be converted to a {@code LocalDateTime}
1682      * @throws UnsupportedTemporalTypeException if the unit is not supported
1683      * @throws ArithmeticException if numeric overflow occurs
1684      */
1685     @Override
1686     public long until(Temporal endExclusive, TemporalUnit unit) {
1687         LocalDateTime end = LocalDateTime.from(endExclusive);
1688         if (unit instanceof ChronoUnit chronoUnit) {
1689             if (unit.isTimeBased()) {
1690                 long amount = date.daysUntil(end.date);
1691                 if (amount == 0) {
1692                     return time.until(end.time, unit);
1693                 }
1694                 long timePart = end.time.toNanoOfDay() - time.toNanoOfDay();
1695                 if (amount > 0) {
1696                     amount--;  // safe
1697                     timePart += NANOS_PER_DAY;  // safe
1698                 } else {
1699                     amount++;  // safe
1700                     timePart -= NANOS_PER_DAY;  // safe
1701                 }
1702                 switch (chronoUnit) {
1703                     case NANOS:
1704                         amount = Math.multiplyExact(amount, NANOS_PER_DAY);
1705                         break;
1706                     case MICROS:
1707                         amount = Math.multiplyExact(amount, MICROS_PER_DAY);
1708                         timePart = timePart / 1000;
1709                         break;
1710                     case MILLIS:
1711                         amount = Math.multiplyExact(amount, MILLIS_PER_DAY);
1712                         timePart = timePart / 1_000_000;
1713                         break;
1714                     case SECONDS:
1715                         amount = Math.multiplyExact(amount, SECONDS_PER_DAY);
1716                         timePart = timePart / NANOS_PER_SECOND;
1717                         break;
1718                     case MINUTES:
1719                         amount = Math.multiplyExact(amount, MINUTES_PER_DAY);
1720                         timePart = timePart / NANOS_PER_MINUTE;
1721                         break;
1722                     case HOURS:
1723                         amount = Math.multiplyExact(amount, HOURS_PER_DAY);
1724                         timePart = timePart / NANOS_PER_HOUR;
1725                         break;
1726                     case HALF_DAYS:
1727                         amount = Math.multiplyExact(amount, 2);
1728                         timePart = timePart / (NANOS_PER_HOUR * 12);
1729                         break;
1730                 }
1731                 return Math.addExact(amount, timePart);
1732             }
1733             LocalDate endDate = end.date;
1734             if (endDate.isAfter(date) && end.time.isBefore(time)) {
1735                 endDate = endDate.minusDays(1);
1736             } else if (endDate.isBefore(date) && end.time.isAfter(time)) {
1737                 endDate = endDate.plusDays(1);
1738             }
1739             return date.until(endDate, unit);
1740         }
1741         return unit.between(this, end);
1742     }
1743 
1744     /**
1745      * Formats this date-time using the specified formatter.
1746      * <p>
1747      * This date-time will be passed to the formatter to produce a string.
1748      *
1749      * @param formatter  the formatter to use, not null
1750      * @return the formatted date-time string, not null
1751      * @throws DateTimeException if an error occurs during printing
1752      */
1753     @Override  // override for Javadoc and performance
1754     public String format(DateTimeFormatter formatter) {
1755         Objects.requireNonNull(formatter, "formatter");
1756         return formatter.format(this);
1757     }
1758 
1759     //-----------------------------------------------------------------------
1760     /**
1761      * Combines this date-time with an offset to create an {@code OffsetDateTime}.
1762      * <p>
1763      * This returns an {@code OffsetDateTime} formed from this date-time at the specified offset.
1764      * All possible combinations of date-time and offset are valid.
1765      *
1766      * @param offset  the offset to combine with, not null
1767      * @return the offset date-time formed from this date-time and the specified offset, not null
1768      */
1769     public OffsetDateTime atOffset(ZoneOffset offset) {
1770         return OffsetDateTime.of(this, offset);
1771     }
1772 
1773     /**
1774      * Combines this date-time with a time-zone to create a {@code ZonedDateTime}.
1775      * <p>
1776      * This returns a {@code ZonedDateTime} formed from this date-time at the
1777      * specified time-zone. The result will match this date-time as closely as possible.
1778      * Time-zone rules, such as daylight savings, mean that not every local date-time
1779      * is valid for the specified zone, thus the local date-time may be adjusted.
1780      * <p>
1781      * The local date-time is resolved to a single instant on the time-line.
1782      * This is achieved by finding a valid offset from UTC/Greenwich for the local
1783      * date-time as defined by the {@link ZoneRules rules} of the zone ID.
1784      *<p>
1785      * In most cases, there is only one valid offset for a local date-time.
1786      * In the case of an overlap, where clocks are set back, there are two valid offsets.
1787      * This method uses the earlier offset typically corresponding to "summer".
1788      * <p>
1789      * In the case of a gap, where clocks jump forward, there is no valid offset.
1790      * Instead, the local date-time is adjusted to be later by the length of the gap.
1791      * For a typical one hour daylight savings change, the local date-time will be
1792      * moved one hour later into the offset typically corresponding to "summer".
1793      * <p>
1794      * To obtain the later offset during an overlap, call
1795      * {@link ZonedDateTime#withLaterOffsetAtOverlap()} on the result of this method.
1796      * To throw an exception when there is a gap or overlap, use
1797      * {@link ZonedDateTime#ofStrict(LocalDateTime, ZoneOffset, ZoneId)}.
1798      *
1799      * @param zone  the time-zone to use, not null
1800      * @return the zoned date-time formed from this date-time, not null
1801      */
1802     @Override
1803     public ZonedDateTime atZone(ZoneId zone) {
1804         return ZonedDateTime.of(this, zone);
1805     }
1806 
1807     //-----------------------------------------------------------------------
1808     /**
1809      * Compares this date-time to another date-time.
1810      * <p>
1811      * The comparison is primarily based on the date-time, from earliest to latest.
1812      * It is "consistent with equals", as defined by {@link Comparable}.
1813      * <p>
1814      * If all the date-times being compared are instances of {@code LocalDateTime},
1815      * then the comparison will be entirely based on the date-time.
1816      * If some dates being compared are in different chronologies, then the
1817      * chronology is also considered, see {@link ChronoLocalDateTime#compareTo}.
1818      *
1819      * @param other  the other date-time to compare to, not null
1820      * @return the comparator value, that is the comparison of this local date-time with
1821      *          the {@code other} local date-time and this chronology with the {@code other} chronology,
1822      *          in order, returning the first non-zero result, and otherwise returning zero
1823      * @see #isBefore
1824      * @see #isAfter
1825      */
1826     @Override  // override for Javadoc and performance
1827     public int compareTo(ChronoLocalDateTime<?> other) {
1828         if (other instanceof LocalDateTime) {
1829             return compareTo0((LocalDateTime) other);
1830         }
1831         return ChronoLocalDateTime.super.compareTo(other);
1832     }
1833 
1834     private int compareTo0(LocalDateTime other) {
1835         int cmp = date.compareTo0(other.toLocalDate());
1836         if (cmp == 0) {
1837             cmp = time.compareTo(other.toLocalTime());
1838         }
1839         return cmp;
1840     }
1841 
1842     /**
1843      * Checks if this date-time is after the specified date-time.
1844      * <p>
1845      * This checks to see if this date-time represents a point on the
1846      * local time-line after the other date-time.
1847      * <pre>
1848      *   LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
1849      *   LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
1850      *   a.isAfter(b) == false
1851      *   a.isAfter(a) == false
1852      *   b.isAfter(a) == true
1853      * </pre>
1854      * <p>
1855      * This method only considers the position of the two date-times on the local time-line.
1856      * It does not take into account the chronology, or calendar system.
1857      * This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},
1858      * but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.
1859      *
1860      * @param other  the other date-time to compare to, not null
1861      * @return true if this date-time is after the specified date-time
1862      */
1863     @Override  // override for Javadoc and performance
1864     public boolean isAfter(ChronoLocalDateTime<?> other) {
1865         if (other instanceof LocalDateTime) {
1866             return compareTo0((LocalDateTime) other) > 0;
1867         }
1868         return ChronoLocalDateTime.super.isAfter(other);
1869     }
1870 
1871     /**
1872      * Checks if this date-time is before the specified date-time.
1873      * <p>
1874      * This checks to see if this date-time represents a point on the
1875      * local time-line before the other date-time.
1876      * <pre>
1877      *   LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
1878      *   LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
1879      *   a.isBefore(b) == true
1880      *   a.isBefore(a) == false
1881      *   b.isBefore(a) == false
1882      * </pre>
1883      * <p>
1884      * This method only considers the position of the two date-times on the local time-line.
1885      * It does not take into account the chronology, or calendar system.
1886      * This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},
1887      * but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.
1888      *
1889      * @param other  the other date-time to compare to, not null
1890      * @return true if this date-time is before the specified date-time
1891      */
1892     @Override  // override for Javadoc and performance
1893     public boolean isBefore(ChronoLocalDateTime<?> other) {
1894         if (other instanceof LocalDateTime) {
1895             return compareTo0((LocalDateTime) other) < 0;
1896         }
1897         return ChronoLocalDateTime.super.isBefore(other);
1898     }
1899 
1900     /**
1901      * Checks if this date-time is equal to the specified date-time.
1902      * <p>
1903      * This checks to see if this date-time represents the same point on the
1904      * local time-line as the other date-time.
1905      * <pre>
1906      *   LocalDate a = LocalDateTime.of(2012, 6, 30, 12, 00);
1907      *   LocalDate b = LocalDateTime.of(2012, 7, 1, 12, 00);
1908      *   a.isEqual(b) == false
1909      *   a.isEqual(a) == true
1910      *   b.isEqual(a) == false
1911      * </pre>
1912      * <p>
1913      * This method only considers the position of the two date-times on the local time-line.
1914      * It does not take into account the chronology, or calendar system.
1915      * This is different from the comparison in {@link #compareTo(ChronoLocalDateTime)},
1916      * but is the same approach as {@link ChronoLocalDateTime#timeLineOrder()}.
1917      *
1918      * @param other  the other date-time to compare to, not null
1919      * @return true if this date-time is equal to the specified date-time
1920      */
1921     @Override  // override for Javadoc and performance
1922     public boolean isEqual(ChronoLocalDateTime<?> other) {
1923         if (other instanceof LocalDateTime) {
1924             return compareTo0((LocalDateTime) other) == 0;
1925         }
1926         return ChronoLocalDateTime.super.isEqual(other);
1927     }
1928 
1929     //-----------------------------------------------------------------------
1930     /**
1931      * Checks if this date-time is equal to another date-time.
1932      * <p>
1933      * Compares this {@code LocalDateTime} with another ensuring that the date-time is the same.
1934      * Only objects of type {@code LocalDateTime} are compared, other types return false.
1935      *
1936      * @param obj  the object to check, null returns false
1937      * @return true if this is equal to the other date-time
1938      */
1939     @Override
1940     public boolean equals(Object obj) {
1941         if (this == obj) {
1942             return true;
1943         }
1944         return (obj instanceof LocalDateTime other)
1945                 && date.equals(other.date)
1946                 && time.equals(other.time);
1947     }
1948 
1949     /**
1950      * A hash code for this date-time.
1951      *
1952      * @return a suitable hash code
1953      */
1954     @Override
1955     public int hashCode() {
1956         return date.hashCode() ^ time.hashCode();
1957     }
1958 
1959     //-----------------------------------------------------------------------
1960     /**
1961      * Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}.
1962      * <p>
1963      * The output will be one of the following ISO-8601 formats:
1964      * <ul>
1965      * <li>{@code uuuu-MM-dd'T'HH:mm}</li>
1966      * <li>{@code uuuu-MM-dd'T'HH:mm:ss}</li>
1967      * <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSS}</li>
1968      * <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSS}</li>
1969      * <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS}</li>
1970      * </ul>
1971      * The format used will be the shortest that outputs the full value of
1972      * the time where the omitted parts are implied to be zero.
1973      *
1974      * @return a string representation of this date-time, not null
1975      */
1976     @Override
1977     public String toString() {
1978         var buf = new StringBuilder(29);
1979         DateTimeHelper.formatTo(buf, this);
1980         return buf.toString();
1981     }
1982 
1983 
1984     //-----------------------------------------------------------------------
1985     /**
1986      * Writes the object using a
1987      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1988      * @serialData
1989      * <pre>
1990      *  out.writeByte(5);  // identifies a LocalDateTime
1991      *  // the <a href="{@docRoot}/serialized-form.html#java.time.LocalDate">date</a> excluding the one byte header
1992      *  // the <a href="{@docRoot}/serialized-form.html#java.time.LocalTime">time</a> excluding the one byte header
1993      * </pre>
1994      *
1995      * @return the instance of {@code Ser}, not null
1996      */
1997     @java.io.Serial
1998     private Object writeReplace() {
1999         return new Ser(Ser.LOCAL_DATE_TIME_TYPE, this);
2000     }
2001 
2002     /**
2003      * Defend against malicious streams.
2004      *
2005      * @param s the stream to read
2006      * @throws InvalidObjectException always
2007      */
2008     @java.io.Serial
2009     private void readObject(ObjectInputStream s) throws InvalidObjectException {
2010         throw new InvalidObjectException("Deserialization via serialization delegate");
2011     }
2012 
2013     void writeExternal(DataOutput out) throws IOException {
2014         date.writeExternal(out);
2015         time.writeExternal(out);
2016     }
2017 
2018     static LocalDateTime readExternal(DataInput in) throws IOException {
2019         LocalDate date = LocalDate.readExternal(in);
2020         LocalTime time = LocalTime.readExternal(in);
2021         return LocalDateTime.of(date, time);
2022     }
2023 }