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