Path: blob/master/src/java.base/share/classes/java/time/zone/ZoneOffsetTransitionRule.java
41159 views
/*1* Copyright (c) 2012, 2020, 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 timeDefinition 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* @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value170*/171public static ZoneOffsetTransitionRule of(172Month month,173int dayOfMonthIndicator,174DayOfWeek dayOfWeek,175LocalTime time,176boolean timeEndOfDay,177TimeDefinition timeDefinition,178ZoneOffset standardOffset,179ZoneOffset offsetBefore,180ZoneOffset offsetAfter) {181Objects.requireNonNull(month, "month");182Objects.requireNonNull(time, "time");183Objects.requireNonNull(timeDefinition, "timeDefinition");184Objects.requireNonNull(standardOffset, "standardOffset");185Objects.requireNonNull(offsetBefore, "offsetBefore");186Objects.requireNonNull(offsetAfter, "offsetAfter");187if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) {188throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero");189}190if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) {191throw new IllegalArgumentException("Time must be midnight when end of day flag is true");192}193if (time.getNano() != 0) {194throw new IllegalArgumentException("Time's nano-of-second must be zero");195}196return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefinition, standardOffset, offsetBefore, offsetAfter);197}198199/**200* Creates an instance defining the yearly rule to create transitions between two offsets.201*202* @param month the month of the month-day of the first day of the cutover week, not null203* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that204* day or later, negative if the week is that day or earlier, counting from the last day of the month,205* from -28 to 31 excluding 0206* @param dayOfWeek the required day-of-week, null if the month-day should not be changed207* @param time the cutover time in the 'before' offset, not null208* @param timeEndOfDay whether the time is midnight at the end of day209* @param timeDefinition how to interpret the cutover210* @param standardOffset the standard offset in force at the cutover, not null211* @param offsetBefore the offset before the cutover, not null212* @param offsetAfter the offset after the cutover, not null213* @throws IllegalArgumentException if the day of month indicator is invalid214* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight215*/216ZoneOffsetTransitionRule(217Month month,218int dayOfMonthIndicator,219DayOfWeek dayOfWeek,220LocalTime time,221boolean timeEndOfDay,222TimeDefinition timeDefinition,223ZoneOffset standardOffset,224ZoneOffset offsetBefore,225ZoneOffset offsetAfter) {226assert time.getNano() == 0;227this.month = month;228this.dom = (byte) dayOfMonthIndicator;229this.dow = dayOfWeek;230this.time = time;231this.timeEndOfDay = timeEndOfDay;232this.timeDefinition = timeDefinition;233this.standardOffset = standardOffset;234this.offsetBefore = offsetBefore;235this.offsetAfter = offsetAfter;236}237238//-----------------------------------------------------------------------239/**240* Defend against malicious streams.241*242* @param s the stream to read243* @throws InvalidObjectException always244*/245private void readObject(ObjectInputStream s) throws InvalidObjectException {246throw new InvalidObjectException("Deserialization via serialization delegate");247}248249/**250* Writes the object using a251* <a href="{@docRoot}/serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.252* @serialData253* Refer to the serialized form of254* <a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>255* for the encoding of epoch seconds and offsets.256* <pre style="font-size:1.0em">{@code257*258* out.writeByte(3); // identifies a ZoneOffsetTransitionRule259* final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());260* final int stdOffset = standardOffset.getTotalSeconds();261* final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;262* final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;263* final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);264* final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);265* final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);266* final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);267* final int dowByte = (dow == null ? 0 : dow.getValue());268* int b = (month.getValue() << 28) + // 4 bits269* ((dom + 32) << 22) + // 6 bits270* (dowByte << 19) + // 3 bits271* (timeByte << 14) + // 5 bits272* (timeDefinition.ordinal() << 12) + // 2 bits273* (stdOffsetByte << 4) + // 8 bits274* (beforeByte << 2) + // 2 bits275* afterByte; // 2 bits276* out.writeInt(b);277* if (timeByte == 31) {278* out.writeInt(timeSecs);279* }280* if (stdOffsetByte == 255) {281* out.writeInt(stdOffset);282* }283* if (beforeByte == 3) {284* out.writeInt(offsetBefore.getTotalSeconds());285* }286* if (afterByte == 3) {287* out.writeInt(offsetAfter.getTotalSeconds());288* }289* }290* </pre>291*292* @return the replacing object, not null293*/294private Object writeReplace() {295return new Ser(Ser.ZOTRULE, this);296}297298/**299* Writes the state to the stream.300*301* @param out the output stream, not null302* @throws IOException if an error occurs303*/304void writeExternal(DataOutput out) throws IOException {305final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());306final int stdOffset = standardOffset.getTotalSeconds();307final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;308final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;309final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);310final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);311final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);312final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);313final int dowByte = (dow == null ? 0 : dow.getValue());314int b = (month.getValue() << 28) + // 4 bits315((dom + 32) << 22) + // 6 bits316(dowByte << 19) + // 3 bits317(timeByte << 14) + // 5 bits318(timeDefinition.ordinal() << 12) + // 2 bits319(stdOffsetByte << 4) + // 8 bits320(beforeByte << 2) + // 2 bits321afterByte; // 2 bits322out.writeInt(b);323if (timeByte == 31) {324out.writeInt(timeSecs);325}326if (stdOffsetByte == 255) {327out.writeInt(stdOffset);328}329if (beforeByte == 3) {330out.writeInt(offsetBefore.getTotalSeconds());331}332if (afterByte == 3) {333out.writeInt(offsetAfter.getTotalSeconds());334}335}336337/**338* Reads the state from the stream.339*340* @param in the input stream, not null341* @return the created object, not null342* @throws IOException if an error occurs343*/344static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException {345int data = in.readInt();346Month month = Month.of(data >>> 28);347int dom = ((data & (63 << 22)) >>> 22) - 32;348int dowByte = (data & (7 << 19)) >>> 19;349DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte);350int timeByte = (data & (31 << 14)) >>> 14;351TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12];352int stdByte = (data & (255 << 4)) >>> 4;353int beforeByte = (data & (3 << 2)) >>> 2;354int afterByte = (data & 3);355LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0));356ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900));357ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800));358ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800));359return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after);360}361362//-----------------------------------------------------------------------363/**364* Gets the month of the transition.365* <p>366* If the rule defines an exact date then the month is the month of that date.367* <p>368* If the rule defines a week where the transition might occur, then the month369* if the month of either the earliest or latest possible date of the cutover.370*371* @return the month of the transition, not null372*/373public Month getMonth() {374return month;375}376377/**378* Gets the indicator of the day-of-month of the transition.379* <p>380* If the rule defines an exact date then the day is the month of that date.381* <p>382* If the rule defines a week where the transition might occur, then the day383* defines either the start of the end of the transition week.384* <p>385* If the value is positive, then it represents a normal day-of-month, and is the386* earliest possible date that the transition can be.387* The date may refer to 29th February which should be treated as 1st March in non-leap years.388* <p>389* If the value is negative, then it represents the number of days back from the390* end of the month where {@code -1} is the last day of the month.391* In this case, the day identified is the latest possible date that the transition can be.392*393* @return the day-of-month indicator, from -28 to 31 excluding 0394*/395public int getDayOfMonthIndicator() {396return dom;397}398399/**400* Gets the day-of-week of the transition.401* <p>402* If the rule defines an exact date then this returns null.403* <p>404* If the rule defines a week where the cutover might occur, then this method405* returns the day-of-week that the month-day will be adjusted to.406* If the day is positive then the adjustment is later.407* If the day is negative then the adjustment is earlier.408*409* @return the day-of-week that the transition occurs, null if the rule defines an exact date410*/411public DayOfWeek getDayOfWeek() {412return dow;413}414415/**416* Gets the local time of day of the transition which must be checked with417* {@link #isMidnightEndOfDay()}.418* <p>419* The time is converted into an instant using the time definition.420*421* @return the local time of day of the transition, not null422*/423public LocalTime getLocalTime() {424return time;425}426427/**428* Is the transition local time midnight at the end of day.429* <p>430* The transition may be represented as occurring at 24:00.431*432* @return whether a local time of midnight is at the start or end of the day433*/434public boolean isMidnightEndOfDay() {435return timeEndOfDay;436}437438/**439* Gets the time definition, specifying how to convert the time to an instant.440* <p>441* The local time can be converted to an instant using the standard offset,442* the wall offset or UTC.443*444* @return the time definition, not null445*/446public TimeDefinition getTimeDefinition() {447return timeDefinition;448}449450/**451* Gets the standard offset in force at the transition.452*453* @return the standard offset, not null454*/455public ZoneOffset getStandardOffset() {456return standardOffset;457}458459/**460* Gets the offset before the transition.461*462* @return the offset before, not null463*/464public ZoneOffset getOffsetBefore() {465return offsetBefore;466}467468/**469* Gets the offset after the transition.470*471* @return the offset after, not null472*/473public ZoneOffset getOffsetAfter() {474return offsetAfter;475}476477//-----------------------------------------------------------------------478/**479* Creates a transition instance for the specified year.480* <p>481* Calculations are performed using the ISO-8601 chronology.482*483* @param year the year to create a transition for, not null484* @return the transition instance, not null485*/486public ZoneOffsetTransition createTransition(int year) {487LocalDate date;488if (dom < 0) {489date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom);490if (dow != null) {491date = date.with(previousOrSame(dow));492}493} else {494date = LocalDate.of(year, month, dom);495if (dow != null) {496date = date.with(nextOrSame(dow));497}498}499if (timeEndOfDay) {500date = date.plusDays(1);501}502LocalDateTime localDT = LocalDateTime.of(date, time);503LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore);504return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);505}506507//-----------------------------------------------------------------------508/**509* Checks if this object equals another.510* <p>511* The entire state of the object is compared.512*513* @param otherRule the other object to compare to, null returns false514* @return true if equal515*/516@Override517public boolean equals(Object otherRule) {518if (otherRule == this) {519return true;520}521return (otherRule instanceof ZoneOffsetTransitionRule other)522&& month == other.month523&& dom == other.dom524&& dow == other.dow525&& timeDefinition == other.timeDefinition526&& timeEndOfDay == other.timeEndOfDay527&& time.equals(other.time)528&& standardOffset.equals(other.standardOffset)529&& offsetBefore.equals(other.offsetBefore)530&& offsetAfter.equals(other.offsetAfter);531}532533/**534* Returns a suitable hash code.535*536* @return the hash code537*/538@Override539public int hashCode() {540int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) +541(month.ordinal() << 11) + ((dom + 32) << 5) +542((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal());543return hash ^ standardOffset.hashCode() ^544offsetBefore.hashCode() ^ offsetAfter.hashCode();545}546547//-----------------------------------------------------------------------548/**549* Returns a string describing this object.550*551* @return a string for debugging, not null552*/553@Override554public String toString() {555StringBuilder buf = new StringBuilder();556buf.append("TransitionRule[")557.append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ")558.append(offsetBefore).append(" to ").append(offsetAfter).append(", ");559if (dow != null) {560if (dom == -1) {561buf.append(dow.name()).append(" on or before last day of ").append(month.name());562} else if (dom < 0) {563buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name());564} else {565buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom);566}567} else {568buf.append(month.name()).append(' ').append(dom);569}570buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString())571.append(" ").append(timeDefinition)572.append(", standard offset ").append(standardOffset)573.append(']');574return buf.toString();575}576577//-----------------------------------------------------------------------578/**579* A definition of the way a local time can be converted to the actual580* transition date-time.581* <p>582* Time zone rules are expressed in one of three ways:583* <ul>584* <li>Relative to UTC</li>585* <li>Relative to the standard offset in force</li>586* <li>Relative to the wall offset (what you would see on a clock on the wall)</li>587* </ul>588*/589public static enum TimeDefinition {590/** The local date-time is expressed in terms of the UTC offset. */591UTC,592/** The local date-time is expressed in terms of the wall offset. */593WALL,594/** The local date-time is expressed in terms of the standard offset. */595STANDARD;596597/**598* Converts the specified local date-time to the local date-time actually599* seen on a wall clock.600* <p>601* This method converts using the type of this enum.602* The output is defined relative to the 'before' offset of the transition.603* <p>604* The UTC type uses the UTC offset.605* The STANDARD type uses the standard offset.606* The WALL type returns the input date-time.607* The result is intended for use with the wall-offset.608*609* @param dateTime the local date-time, not null610* @param standardOffset the standard offset, not null611* @param wallOffset the wall offset, not null612* @return the date-time relative to the wall/before offset, not null613*/614public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) {615switch (this) {616case UTC: {617int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds();618return dateTime.plusSeconds(difference);619}620case STANDARD: {621int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds();622return dateTime.plusSeconds(difference);623}624default: // WALL625return dateTime;626}627}628}629630}631632633