Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/zone/ZoneOffsetTransition.java
38918 views
/*1* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.zone;6263import java.io.DataInput;64import java.io.DataOutput;65import java.io.IOException;66import java.io.InvalidObjectException;67import java.io.ObjectInputStream;68import java.io.Serializable;69import java.time.Duration;70import java.time.Instant;71import java.time.LocalDateTime;72import java.time.ZoneOffset;73import java.util.Arrays;74import java.util.Collections;75import java.util.List;76import java.util.Objects;7778/**79* A transition between two offsets caused by a discontinuity in the local time-line.80* <p>81* A transition between two offsets is normally the result of a daylight savings cutover.82* The discontinuity is normally a gap in spring and an overlap in autumn.83* {@code ZoneOffsetTransition} models the transition between the two offsets.84* <p>85* Gaps occur where there are local date-times that simply do not exist.86* An example would be when the offset changes from {@code +03:00} to {@code +04:00}.87* This might be described as 'the clocks will move forward one hour tonight at 1am'.88* <p>89* Overlaps occur where there are local date-times that exist twice.90* An example would be when the offset changes from {@code +04:00} to {@code +03:00}.91* This might be described as 'the clocks will move back one hour tonight at 2am'.92*93* @implSpec94* This class is immutable and thread-safe.95*96* @since 1.897*/98public final class ZoneOffsetTransition99implements Comparable<ZoneOffsetTransition>, Serializable {100101/**102* Serialization version.103*/104private static final long serialVersionUID = -6946044323557704546L;105/**106* The local transition date-time at the transition.107*/108private final LocalDateTime transition;109/**110* The offset before transition.111*/112private final ZoneOffset offsetBefore;113/**114* The offset after transition.115*/116private final ZoneOffset offsetAfter;117118//-----------------------------------------------------------------------119/**120* Obtains an instance defining a transition between two offsets.121* <p>122* Applications should normally obtain an instance from {@link ZoneRules}.123* This factory is only intended for use when creating {@link ZoneRules}.124*125* @param transition the transition date-time at the transition, which never126* actually occurs, expressed local to the before offset, not null127* @param offsetBefore the offset before the transition, not null128* @param offsetAfter the offset at and after the transition, not null129* @return the transition, not null130* @throws IllegalArgumentException if {@code offsetBefore} and {@code offsetAfter}131* are equal, or {@code transition.getNano()} returns non-zero value132*/133public static ZoneOffsetTransition of(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {134Objects.requireNonNull(transition, "transition");135Objects.requireNonNull(offsetBefore, "offsetBefore");136Objects.requireNonNull(offsetAfter, "offsetAfter");137if (offsetBefore.equals(offsetAfter)) {138throw new IllegalArgumentException("Offsets must not be equal");139}140if (transition.getNano() != 0) {141throw new IllegalArgumentException("Nano-of-second must be zero");142}143return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);144}145146/**147* Creates an instance defining a transition between two offsets.148*149* @param transition the transition date-time with the offset before the transition, not null150* @param offsetBefore the offset before the transition, not null151* @param offsetAfter the offset at and after the transition, not null152*/153ZoneOffsetTransition(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {154this.transition = transition;155this.offsetBefore = offsetBefore;156this.offsetAfter = offsetAfter;157}158159/**160* Creates an instance from epoch-second and offsets.161*162* @param epochSecond the transition epoch-second163* @param offsetBefore the offset before the transition, not null164* @param offsetAfter the offset at and after the transition, not null165*/166ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {167this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore);168this.offsetBefore = offsetBefore;169this.offsetAfter = offsetAfter;170}171172//-----------------------------------------------------------------------173/**174* Defend against malicious streams.175*176* @param s the stream to read177* @throws InvalidObjectException always178*/179private void readObject(ObjectInputStream s) throws InvalidObjectException {180throw new InvalidObjectException("Deserialization via serialization delegate");181}182183/**184* Writes the object using a185* <a href="../../../serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.186* @serialData187* Refer to the serialized form of188* <a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>189* for the encoding of epoch seconds and offsets.190* <pre style="font-size:1.0em">{@code191*192* out.writeByte(2); // identifies a ZoneOffsetTransition193* out.writeEpochSec(toEpochSecond);194* out.writeOffset(offsetBefore);195* out.writeOffset(offsetAfter);196* }197* </pre>198* @return the replacing object, not null199*/200private Object writeReplace() {201return new Ser(Ser.ZOT, this);202}203204/**205* Writes the state to the stream.206*207* @param out the output stream, not null208* @throws IOException if an error occurs209*/210void writeExternal(DataOutput out) throws IOException {211Ser.writeEpochSec(toEpochSecond(), out);212Ser.writeOffset(offsetBefore, out);213Ser.writeOffset(offsetAfter, out);214}215216/**217* Reads the state from the stream.218*219* @param in the input stream, not null220* @return the created object, not null221* @throws IOException if an error occurs222*/223static ZoneOffsetTransition readExternal(DataInput in) throws IOException {224long epochSecond = Ser.readEpochSec(in);225ZoneOffset before = Ser.readOffset(in);226ZoneOffset after = Ser.readOffset(in);227if (before.equals(after)) {228throw new IllegalArgumentException("Offsets must not be equal");229}230return new ZoneOffsetTransition(epochSecond, before, after);231}232233//-----------------------------------------------------------------------234/**235* Gets the transition instant.236* <p>237* This is the instant of the discontinuity, which is defined as the first238* instant that the 'after' offset applies.239* <p>240* The methods {@link #getInstant()}, {@link #getDateTimeBefore()} and {@link #getDateTimeAfter()}241* all represent the same instant.242*243* @return the transition instant, not null244*/245public Instant getInstant() {246return transition.toInstant(offsetBefore);247}248249/**250* Gets the transition instant as an epoch second.251*252* @return the transition epoch second253*/254public long toEpochSecond() {255return transition.toEpochSecond(offsetBefore);256}257258//-------------------------------------------------------------------------259/**260* Gets the local transition date-time, as would be expressed with the 'before' offset.261* <p>262* This is the date-time where the discontinuity begins expressed with the 'before' offset.263* At this instant, the 'after' offset is actually used, therefore the combination of this264* date-time and the 'before' offset will never occur.265* <p>266* The combination of the 'before' date-time and offset represents the same instant267* as the 'after' date-time and offset.268*269* @return the transition date-time expressed with the before offset, not null270*/271public LocalDateTime getDateTimeBefore() {272return transition;273}274275/**276* Gets the local transition date-time, as would be expressed with the 'after' offset.277* <p>278* This is the first date-time after the discontinuity, when the new offset applies.279* <p>280* The combination of the 'before' date-time and offset represents the same instant281* as the 'after' date-time and offset.282*283* @return the transition date-time expressed with the after offset, not null284*/285public LocalDateTime getDateTimeAfter() {286return transition.plusSeconds(getDurationSeconds());287}288289/**290* Gets the offset before the transition.291* <p>292* This is the offset in use before the instant of the transition.293*294* @return the offset before the transition, not null295*/296public ZoneOffset getOffsetBefore() {297return offsetBefore;298}299300/**301* Gets the offset after the transition.302* <p>303* This is the offset in use on and after the instant of the transition.304*305* @return the offset after the transition, not null306*/307public ZoneOffset getOffsetAfter() {308return offsetAfter;309}310311/**312* Gets the duration of the transition.313* <p>314* In most cases, the transition duration is one hour, however this is not always the case.315* The duration will be positive for a gap and negative for an overlap.316* Time-zones are second-based, so the nanosecond part of the duration will be zero.317*318* @return the duration of the transition, positive for gaps, negative for overlaps319*/320public Duration getDuration() {321return Duration.ofSeconds(getDurationSeconds());322}323324/**325* Gets the duration of the transition in seconds.326*327* @return the duration in seconds328*/329private int getDurationSeconds() {330return getOffsetAfter().getTotalSeconds() - getOffsetBefore().getTotalSeconds();331}332333/**334* Does this transition represent a gap in the local time-line.335* <p>336* Gaps occur where there are local date-times that simply do not exist.337* An example would be when the offset changes from {@code +01:00} to {@code +02:00}.338* This might be described as 'the clocks will move forward one hour tonight at 1am'.339*340* @return true if this transition is a gap, false if it is an overlap341*/342public boolean isGap() {343return getOffsetAfter().getTotalSeconds() > getOffsetBefore().getTotalSeconds();344}345346/**347* Does this transition represent an overlap in the local time-line.348* <p>349* Overlaps occur where there are local date-times that exist twice.350* An example would be when the offset changes from {@code +02:00} to {@code +01:00}.351* This might be described as 'the clocks will move back one hour tonight at 2am'.352*353* @return true if this transition is an overlap, false if it is a gap354*/355public boolean isOverlap() {356return getOffsetAfter().getTotalSeconds() < getOffsetBefore().getTotalSeconds();357}358359/**360* Checks if the specified offset is valid during this transition.361* <p>362* This checks to see if the given offset will be valid at some point in the transition.363* A gap will always return false.364* An overlap will return true if the offset is either the before or after offset.365*366* @param offset the offset to check, null returns false367* @return true if the offset is valid during the transition368*/369public boolean isValidOffset(ZoneOffset offset) {370return isGap() ? false : (getOffsetBefore().equals(offset) || getOffsetAfter().equals(offset));371}372373/**374* Gets the valid offsets during this transition.375* <p>376* A gap will return an empty list, while an overlap will return both offsets.377*378* @return the list of valid offsets379*/380List<ZoneOffset> getValidOffsets() {381if (isGap()) {382return Collections.emptyList();383}384return Arrays.asList(getOffsetBefore(), getOffsetAfter());385}386387//-----------------------------------------------------------------------388/**389* Compares this transition to another based on the transition instant.390* <p>391* This compares the instants of each transition.392* The offsets are ignored, making this order inconsistent with equals.393*394* @param transition the transition to compare to, not null395* @return the comparator value, negative if less, positive if greater396*/397@Override398public int compareTo(ZoneOffsetTransition transition) {399return this.getInstant().compareTo(transition.getInstant());400}401402//-----------------------------------------------------------------------403/**404* Checks if this object equals another.405* <p>406* The entire state of the object is compared.407*408* @param other the other object to compare to, null returns false409* @return true if equal410*/411@Override412public boolean equals(Object other) {413if (other == this) {414return true;415}416if (other instanceof ZoneOffsetTransition) {417ZoneOffsetTransition d = (ZoneOffsetTransition) other;418return transition.equals(d.transition) &&419offsetBefore.equals(d.offsetBefore) && offsetAfter.equals(d.offsetAfter);420}421return false;422}423424/**425* Returns a suitable hash code.426*427* @return the hash code428*/429@Override430public int hashCode() {431return transition.hashCode() ^ offsetBefore.hashCode() ^ Integer.rotateLeft(offsetAfter.hashCode(), 16);432}433434//-----------------------------------------------------------------------435/**436* Returns a string describing this object.437*438* @return a string for debugging, not null439*/440@Override441public String toString() {442StringBuilder buf = new StringBuilder();443buf.append("Transition[")444.append(isGap() ? "Gap" : "Overlap")445.append(" at ")446.append(transition)447.append(offsetBefore)448.append(" to ")449.append(offsetAfter)450.append(']');451return buf.toString();452}453454}455456457