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