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