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