Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/zone/ZoneOffsetTransitionRule.java
38918 views
/*1* Copyright (c) 2012, 2013, 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 static java.time.temporal.TemporalAdjusters.nextOrSame;64import static java.time.temporal.TemporalAdjusters.previousOrSame;6566import java.io.DataInput;67import java.io.DataOutput;68import java.io.IOException;69import java.io.InvalidObjectException;70import java.io.ObjectInputStream;71import java.io.Serializable;72import java.time.DayOfWeek;73import java.time.LocalDate;74import java.time.LocalDateTime;75import java.time.LocalTime;76import java.time.Month;77import java.time.ZoneOffset;78import java.time.chrono.IsoChronology;79import java.util.Objects;8081/**82* A rule expressing how to create a transition.83* <p>84* This class allows rules for identifying future transitions to be expressed.85* A rule might be written in many forms:86* <ul>87* <li>the 16th March88* <li>the Sunday on or after the 16th March89* <li>the Sunday on or before the 16th March90* <li>the last Sunday in February91* </ul>92* These different rule types can be expressed and queried.93*94* @implSpec95* This class is immutable and thread-safe.96*97* @since 1.898*/99public final class ZoneOffsetTransitionRule implements Serializable {100101/**102* Serialization version.103*/104private static final long serialVersionUID = 6889046316657758795L;105106/**107* The month of the month-day of the first day of the cutover week.108* The actual date will be adjusted by the dowChange field.109*/110private final Month month;111/**112* The day-of-month of the month-day of the cutover week.113* If positive, it is the start of the week where the cutover can occur.114* If negative, it represents the end of the week where cutover can occur.115* The value is the number of days from the end of the month, such that116* {@code -1} is the last day of the month, {@code -2} is the second117* to last day, and so on.118*/119private final byte dom;120/**121* The cutover day-of-week, null to retain the day-of-month.122*/123private final DayOfWeek dow;124/**125* The cutover time in the 'before' offset.126*/127private final LocalTime time;128/**129* Whether the cutover time is midnight at the end of day.130*/131private final boolean timeEndOfDay;132/**133* The definition of how the local time should be interpreted.134*/135private final TimeDefinition timeDefinition;136/**137* The standard offset at the cutover.138*/139private final ZoneOffset standardOffset;140/**141* The offset before the cutover.142*/143private final ZoneOffset offsetBefore;144/**145* The offset after the cutover.146*/147private final ZoneOffset offsetAfter;148149/**150* Obtains an instance defining the yearly rule to create transitions between two offsets.151* <p>152* Applications should normally obtain an instance from {@link ZoneRules}.153* This factory is only intended for use when creating {@link ZoneRules}.154*155* @param month the month of the month-day of the first day of the cutover week, not null156* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that157* day or later, negative if the week is that day or earlier, counting from the last day of the month,158* from -28 to 31 excluding 0159* @param dayOfWeek the required day-of-week, null if the month-day should not be changed160* @param time the cutover time in the 'before' offset, not null161* @param timeEndOfDay whether the time is midnight at the end of day162* @param timeDefnition how to interpret the cutover163* @param standardOffset the standard offset in force at the cutover, not null164* @param offsetBefore the offset before the cutover, not null165* @param offsetAfter the offset after the cutover, not null166* @return the rule, not null167* @throws IllegalArgumentException if the day of month indicator is invalid168* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight169*/170public static ZoneOffsetTransitionRule of(171Month month,172int dayOfMonthIndicator,173DayOfWeek dayOfWeek,174LocalTime time,175boolean timeEndOfDay,176TimeDefinition timeDefnition,177ZoneOffset standardOffset,178ZoneOffset offsetBefore,179ZoneOffset offsetAfter) {180Objects.requireNonNull(month, "month");181Objects.requireNonNull(time, "time");182Objects.requireNonNull(timeDefnition, "timeDefnition");183Objects.requireNonNull(standardOffset, "standardOffset");184Objects.requireNonNull(offsetBefore, "offsetBefore");185Objects.requireNonNull(offsetAfter, "offsetAfter");186if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) {187throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero");188}189if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) {190throw new IllegalArgumentException("Time must be midnight when end of day flag is true");191}192return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter);193}194195/**196* Creates an instance defining the yearly rule to create transitions between two offsets.197*198* @param month the month of the month-day of the first day of the cutover week, not null199* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that200* day or later, negative if the week is that day or earlier, counting from the last day of the month,201* from -28 to 31 excluding 0202* @param dayOfWeek the required day-of-week, null if the month-day should not be changed203* @param time the cutover time in the 'before' offset, not null204* @param timeEndOfDay whether the time is midnight at the end of day205* @param timeDefnition how to interpret the cutover206* @param standardOffset the standard offset in force at the cutover, not null207* @param offsetBefore the offset before the cutover, not null208* @param offsetAfter the offset after the cutover, not null209* @throws IllegalArgumentException if the day of month indicator is invalid210* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight211*/212ZoneOffsetTransitionRule(213Month month,214int dayOfMonthIndicator,215DayOfWeek dayOfWeek,216LocalTime time,217boolean timeEndOfDay,218TimeDefinition timeDefnition,219ZoneOffset standardOffset,220ZoneOffset offsetBefore,221ZoneOffset offsetAfter) {222this.month = month;223this.dom = (byte) dayOfMonthIndicator;224this.dow = dayOfWeek;225this.time = time;226this.timeEndOfDay = timeEndOfDay;227this.timeDefinition = timeDefnition;228this.standardOffset = standardOffset;229this.offsetBefore = offsetBefore;230this.offsetAfter = offsetAfter;231}232233//-----------------------------------------------------------------------234/**235* Defend against malicious streams.236*237* @param s the stream to read238* @throws InvalidObjectException always239*/240private void readObject(ObjectInputStream s) throws InvalidObjectException {241throw new InvalidObjectException("Deserialization via serialization delegate");242}243244/**245* Writes the object using a246* <a href="../../../serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.247* @serialData248* Refer to the serialized form of249* <a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>250* for the encoding of epoch seconds and offsets.251* <pre style="font-size:1.0em">{@code252*253* out.writeByte(3); // identifies a ZoneOffsetTransition254* final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());255* final int stdOffset = standardOffset.getTotalSeconds();256* final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;257* final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;258* final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);259* final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);260* final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);261* final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);262* final int dowByte = (dow == null ? 0 : dow.getValue());263* int b = (month.getValue() << 28) + // 4 bits264* ((dom + 32) << 22) + // 6 bits265* (dowByte << 19) + // 3 bits266* (timeByte << 14) + // 5 bits267* (timeDefinition.ordinal() << 12) + // 2 bits268* (stdOffsetByte << 4) + // 8 bits269* (beforeByte << 2) + // 2 bits270* afterByte; // 2 bits271* out.writeInt(b);272* if (timeByte == 31) {273* out.writeInt(timeSecs);274* }275* if (stdOffsetByte == 255) {276* out.writeInt(stdOffset);277* }278* if (beforeByte == 3) {279* out.writeInt(offsetBefore.getTotalSeconds());280* }281* if (afterByte == 3) {282* out.writeInt(offsetAfter.getTotalSeconds());283* }284* }285* </pre>286*287* @return the replacing object, not null288*/289private Object writeReplace() {290return new Ser(Ser.ZOTRULE, this);291}292293/**294* Writes the state to the stream.295*296* @param out the output stream, not null297* @throws IOException if an error occurs298*/299void writeExternal(DataOutput out) throws IOException {300final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());301final int stdOffset = standardOffset.getTotalSeconds();302final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;303final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;304final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);305final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);306final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);307final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);308final int dowByte = (dow == null ? 0 : dow.getValue());309int b = (month.getValue() << 28) + // 4 bits310((dom + 32) << 22) + // 6 bits311(dowByte << 19) + // 3 bits312(timeByte << 14) + // 5 bits313(timeDefinition.ordinal() << 12) + // 2 bits314(stdOffsetByte << 4) + // 8 bits315(beforeByte << 2) + // 2 bits316afterByte; // 2 bits317out.writeInt(b);318if (timeByte == 31) {319out.writeInt(timeSecs);320}321if (stdOffsetByte == 255) {322out.writeInt(stdOffset);323}324if (beforeByte == 3) {325out.writeInt(offsetBefore.getTotalSeconds());326}327if (afterByte == 3) {328out.writeInt(offsetAfter.getTotalSeconds());329}330}331332/**333* Reads the state from the stream.334*335* @param in the input stream, not null336* @return the created object, not null337* @throws IOException if an error occurs338*/339static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException {340int data = in.readInt();341Month month = Month.of(data >>> 28);342int dom = ((data & (63 << 22)) >>> 22) - 32;343int dowByte = (data & (7 << 19)) >>> 19;344DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte);345int timeByte = (data & (31 << 14)) >>> 14;346TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12];347int stdByte = (data & (255 << 4)) >>> 4;348int beforeByte = (data & (3 << 2)) >>> 2;349int afterByte = (data & 3);350LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0));351ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900));352ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800));353ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800));354return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after);355}356357//-----------------------------------------------------------------------358/**359* Gets the month of the transition.360* <p>361* If the rule defines an exact date then the month is the month of that date.362* <p>363* If the rule defines a week where the transition might occur, then the month364* if the month of either the earliest or latest possible date of the cutover.365*366* @return the month of the transition, not null367*/368public Month getMonth() {369return month;370}371372/**373* Gets the indicator of the day-of-month of the transition.374* <p>375* If the rule defines an exact date then the day is the month of that date.376* <p>377* If the rule defines a week where the transition might occur, then the day378* defines either the start of the end of the transition week.379* <p>380* If the value is positive, then it represents a normal day-of-month, and is the381* earliest possible date that the transition can be.382* The date may refer to 29th February which should be treated as 1st March in non-leap years.383* <p>384* If the value is negative, then it represents the number of days back from the385* end of the month where {@code -1} is the last day of the month.386* In this case, the day identified is the latest possible date that the transition can be.387*388* @return the day-of-month indicator, from -28 to 31 excluding 0389*/390public int getDayOfMonthIndicator() {391return dom;392}393394/**395* Gets the day-of-week of the transition.396* <p>397* If the rule defines an exact date then this returns null.398* <p>399* If the rule defines a week where the cutover might occur, then this method400* returns the day-of-week that the month-day will be adjusted to.401* If the day is positive then the adjustment is later.402* If the day is negative then the adjustment is earlier.403*404* @return the day-of-week that the transition occurs, null if the rule defines an exact date405*/406public DayOfWeek getDayOfWeek() {407return dow;408}409410/**411* Gets the local time of day of the transition which must be checked with412* {@link #isMidnightEndOfDay()}.413* <p>414* The time is converted into an instant using the time definition.415*416* @return the local time of day of the transition, not null417*/418public LocalTime getLocalTime() {419return time;420}421422/**423* Is the transition local time midnight at the end of day.424* <p>425* The transition may be represented as occurring at 24:00.426*427* @return whether a local time of midnight is at the start or end of the day428*/429public boolean isMidnightEndOfDay() {430return timeEndOfDay;431}432433/**434* Gets the time definition, specifying how to convert the time to an instant.435* <p>436* The local time can be converted to an instant using the standard offset,437* the wall offset or UTC.438*439* @return the time definition, not null440*/441public TimeDefinition getTimeDefinition() {442return timeDefinition;443}444445/**446* Gets the standard offset in force at the transition.447*448* @return the standard offset, not null449*/450public ZoneOffset getStandardOffset() {451return standardOffset;452}453454/**455* Gets the offset before the transition.456*457* @return the offset before, not null458*/459public ZoneOffset getOffsetBefore() {460return offsetBefore;461}462463/**464* Gets the offset after the transition.465*466* @return the offset after, not null467*/468public ZoneOffset getOffsetAfter() {469return offsetAfter;470}471472//-----------------------------------------------------------------------473/**474* Creates a transition instance for the specified year.475* <p>476* Calculations are performed using the ISO-8601 chronology.477*478* @param year the year to create a transition for, not null479* @return the transition instance, not null480*/481public ZoneOffsetTransition createTransition(int year) {482LocalDate date;483if (dom < 0) {484date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom);485if (dow != null) {486date = date.with(previousOrSame(dow));487}488} else {489date = LocalDate.of(year, month, dom);490if (dow != null) {491date = date.with(nextOrSame(dow));492}493}494if (timeEndOfDay) {495date = date.plusDays(1);496}497LocalDateTime localDT = LocalDateTime.of(date, time);498LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore);499return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);500}501502//-----------------------------------------------------------------------503/**504* Checks if this object equals another.505* <p>506* The entire state of the object is compared.507*508* @param otherRule the other object to compare to, null returns false509* @return true if equal510*/511@Override512public boolean equals(Object otherRule) {513if (otherRule == this) {514return true;515}516if (otherRule instanceof ZoneOffsetTransitionRule) {517ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule;518return month == other.month && dom == other.dom && dow == other.dow &&519timeDefinition == other.timeDefinition &&520time.equals(other.time) &&521timeEndOfDay == other.timeEndOfDay &&522standardOffset.equals(other.standardOffset) &&523offsetBefore.equals(other.offsetBefore) &&524offsetAfter.equals(other.offsetAfter);525}526return false;527}528529/**530* Returns a suitable hash code.531*532* @return the hash code533*/534@Override535public int hashCode() {536int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) +537(month.ordinal() << 11) + ((dom + 32) << 5) +538((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal());539return hash ^ standardOffset.hashCode() ^540offsetBefore.hashCode() ^ offsetAfter.hashCode();541}542543//-----------------------------------------------------------------------544/**545* Returns a string describing this object.546*547* @return a string for debugging, not null548*/549@Override550public String toString() {551StringBuilder buf = new StringBuilder();552buf.append("TransitionRule[")553.append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ")554.append(offsetBefore).append(" to ").append(offsetAfter).append(", ");555if (dow != null) {556if (dom == -1) {557buf.append(dow.name()).append(" on or before last day of ").append(month.name());558} else if (dom < 0) {559buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name());560} else {561buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom);562}563} else {564buf.append(month.name()).append(' ').append(dom);565}566buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString())567.append(" ").append(timeDefinition)568.append(", standard offset ").append(standardOffset)569.append(']');570return buf.toString();571}572573//-----------------------------------------------------------------------574/**575* A definition of the way a local time can be converted to the actual576* transition date-time.577* <p>578* Time zone rules are expressed in one of three ways:579* <ul>580* <li>Relative to UTC</li>581* <li>Relative to the standard offset in force</li>582* <li>Relative to the wall offset (what you would see on a clock on the wall)</li>583* </ul>584*/585public static enum TimeDefinition {586/** The local date-time is expressed in terms of the UTC offset. */587UTC,588/** The local date-time is expressed in terms of the wall offset. */589WALL,590/** The local date-time is expressed in terms of the standard offset. */591STANDARD;592593/**594* Converts the specified local date-time to the local date-time actually595* seen on a wall clock.596* <p>597* This method converts using the type of this enum.598* The output is defined relative to the 'before' offset of the transition.599* <p>600* The UTC type uses the UTC offset.601* The STANDARD type uses the standard offset.602* The WALL type returns the input date-time.603* The result is intended for use with the wall-offset.604*605* @param dateTime the local date-time, not null606* @param standardOffset the standard offset, not null607* @param wallOffset the wall offset, not null608* @return the date-time relative to the wall/before offset, not null609*/610public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) {611switch (this) {612case UTC: {613int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds();614return dateTime.plusSeconds(difference);615}616case STANDARD: {617int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds();618return dateTime.plusSeconds(difference);619}620default: // WALL621return dateTime;622}623}624}625626}627628629