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