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