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