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