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