Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/ChronoZonedDateTimeImpl.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) 2007-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.chrono;6263import static java.time.temporal.ChronoUnit.SECONDS;6465import java.io.IOException;66import java.io.InvalidObjectException;67import java.io.ObjectInput;68import java.io.ObjectInputStream;69import java.io.ObjectOutput;70import java.io.Serializable;71import java.time.Instant;72import java.time.LocalDateTime;73import java.time.ZoneId;74import java.time.ZoneOffset;75import java.time.temporal.ChronoField;76import java.time.temporal.ChronoUnit;77import java.time.temporal.Temporal;78import java.time.temporal.TemporalField;79import java.time.temporal.TemporalUnit;80import java.time.zone.ZoneOffsetTransition;81import java.time.zone.ZoneRules;82import java.util.List;83import java.util.Objects;8485/**86* A date-time with a time-zone in the calendar neutral API.87* <p>88* {@code ZoneChronoDateTime} is an immutable representation of a date-time with a time-zone.89* This class stores all date and time fields, to a precision of nanoseconds,90* as well as a time-zone and zone offset.91* <p>92* The purpose of storing the time-zone is to distinguish the ambiguous case where93* the local time-line overlaps, typically as a result of the end of daylight time.94* Information about the local-time can be obtained using methods on the time-zone.95*96* @implSpec97* This class is immutable and thread-safe.98*99* @serial Document the delegation of this class in the serialized-form specification.100* @param <D> the concrete type for the date of this date-time101* @since 1.8102*/103final class ChronoZonedDateTimeImpl<D extends ChronoLocalDate>104implements ChronoZonedDateTime<D>, Serializable {105106/**107* Serialization version.108*/109private static final long serialVersionUID = -5261813987200935591L;110111/**112* The local date-time.113*/114private final transient ChronoLocalDateTimeImpl<D> dateTime;115/**116* The zone offset.117*/118private final transient ZoneOffset offset;119/**120* The zone ID.121*/122private final transient ZoneId zone;123124//-----------------------------------------------------------------------125/**126* Obtains an instance from a local date-time using the preferred offset if possible.127*128* @param localDateTime the local date-time, not null129* @param zone the zone identifier, not null130* @param preferredOffset the zone offset, null if no preference131* @return the zoned date-time, not null132*/133static <R extends ChronoLocalDate> ChronoZonedDateTime<R> ofBest(134ChronoLocalDateTimeImpl<R> localDateTime, ZoneId zone, ZoneOffset preferredOffset) {135Objects.requireNonNull(localDateTime, "localDateTime");136Objects.requireNonNull(zone, "zone");137if (zone instanceof ZoneOffset) {138return new ChronoZonedDateTimeImpl<>(localDateTime, (ZoneOffset) zone, zone);139}140ZoneRules rules = zone.getRules();141LocalDateTime isoLDT = LocalDateTime.from(localDateTime);142List<ZoneOffset> validOffsets = rules.getValidOffsets(isoLDT);143ZoneOffset offset;144if (validOffsets.size() == 1) {145offset = validOffsets.get(0);146} else if (validOffsets.size() == 0) {147ZoneOffsetTransition trans = rules.getTransition(isoLDT);148localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());149offset = trans.getOffsetAfter();150} else {151if (preferredOffset != null && validOffsets.contains(preferredOffset)) {152offset = preferredOffset;153} else {154offset = validOffsets.get(0);155}156}157Objects.requireNonNull(offset, "offset"); // protect against bad ZoneRules158return new ChronoZonedDateTimeImpl<>(localDateTime, offset, zone);159}160161/**162* Obtains an instance from an instant using the specified time-zone.163*164* @param chrono the chronology, not null165* @param instant the instant, not null166* @param zone the zone identifier, not null167* @return the zoned date-time, not null168*/169static ChronoZonedDateTimeImpl<?> ofInstant(Chronology chrono, Instant instant, ZoneId zone) {170ZoneRules rules = zone.getRules();171ZoneOffset offset = rules.getOffset(instant);172Objects.requireNonNull(offset, "offset"); // protect against bad ZoneRules173LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);174ChronoLocalDateTimeImpl<?> cldt = (ChronoLocalDateTimeImpl<?>)chrono.localDateTime(ldt);175return new ChronoZonedDateTimeImpl<>(cldt, offset, zone);176}177178/**179* Obtains an instance from an {@code Instant}.180*181* @param instant the instant to create the date-time from, not null182* @param zone the time-zone to use, validated not null183* @return the zoned date-time, validated not null184*/185@SuppressWarnings("unchecked")186private ChronoZonedDateTimeImpl<D> create(Instant instant, ZoneId zone) {187return (ChronoZonedDateTimeImpl<D>)ofInstant(getChronology(), instant, zone);188}189190/**191* Casts the {@code Temporal} to {@code ChronoZonedDateTimeImpl} ensuring it bas the specified chronology.192*193* @param chrono the chronology to check for, not null194* @param temporal a date-time to cast, not null195* @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null196* @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl197* or the chronology is not equal this Chronology198*/199static <R extends ChronoLocalDate> ChronoZonedDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) {200@SuppressWarnings("unchecked")201ChronoZonedDateTimeImpl<R> other = (ChronoZonedDateTimeImpl<R>) temporal;202if (chrono.equals(other.getChronology()) == false) {203throw new ClassCastException("Chronology mismatch, required: " + chrono.getId()204+ ", actual: " + other.getChronology().getId());205}206return other;207}208209//-----------------------------------------------------------------------210/**211* Constructor.212*213* @param dateTime the date-time, not null214* @param offset the zone offset, not null215* @param zone the zone ID, not null216*/217private ChronoZonedDateTimeImpl(ChronoLocalDateTimeImpl<D> dateTime, ZoneOffset offset, ZoneId zone) {218this.dateTime = Objects.requireNonNull(dateTime, "dateTime");219this.offset = Objects.requireNonNull(offset, "offset");220this.zone = Objects.requireNonNull(zone, "zone");221}222223//-----------------------------------------------------------------------224@Override225public ZoneOffset getOffset() {226return offset;227}228229@Override230public ChronoZonedDateTime<D> withEarlierOffsetAtOverlap() {231ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));232if (trans != null && trans.isOverlap()) {233ZoneOffset earlierOffset = trans.getOffsetBefore();234if (earlierOffset.equals(offset) == false) {235return new ChronoZonedDateTimeImpl<>(dateTime, earlierOffset, zone);236}237}238return this;239}240241@Override242public ChronoZonedDateTime<D> withLaterOffsetAtOverlap() {243ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));244if (trans != null) {245ZoneOffset offset = trans.getOffsetAfter();246if (offset.equals(getOffset()) == false) {247return new ChronoZonedDateTimeImpl<>(dateTime, offset, zone);248}249}250return this;251}252253//-----------------------------------------------------------------------254@Override255public ChronoLocalDateTime<D> toLocalDateTime() {256return dateTime;257}258259@Override260public ZoneId getZone() {261return zone;262}263264@Override265public ChronoZonedDateTime<D> withZoneSameLocal(ZoneId zone) {266return ofBest(dateTime, zone, offset);267}268269@Override270public ChronoZonedDateTime<D> withZoneSameInstant(ZoneId zone) {271Objects.requireNonNull(zone, "zone");272return this.zone.equals(zone) ? this : create(dateTime.toInstant(offset), zone);273}274275//-----------------------------------------------------------------------276@Override277public boolean isSupported(TemporalField field) {278return field instanceof ChronoField || (field != null && field.isSupportedBy(this));279}280281//-----------------------------------------------------------------------282@Override283public ChronoZonedDateTime<D> with(TemporalField field, long newValue) {284if (field instanceof ChronoField) {285ChronoField f = (ChronoField) field;286switch (f) {287case INSTANT_SECONDS: return plus(newValue - toEpochSecond(), SECONDS);288case OFFSET_SECONDS: {289ZoneOffset offset = ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue));290return create(dateTime.toInstant(offset), zone);291}292}293return ofBest(dateTime.with(field, newValue), zone, offset);294}295return ChronoZonedDateTimeImpl.ensureValid(getChronology(), field.adjustInto(this, newValue));296}297298//-----------------------------------------------------------------------299@Override300public ChronoZonedDateTime<D> plus(long amountToAdd, TemporalUnit unit) {301if (unit instanceof ChronoUnit) {302return with(dateTime.plus(amountToAdd, unit));303}304return ChronoZonedDateTimeImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd)); /// TODO: Generics replacement Risk!305}306307//-----------------------------------------------------------------------308@Override309public long until(Temporal endExclusive, TemporalUnit unit) {310Objects.requireNonNull(endExclusive, "endExclusive");311@SuppressWarnings("unchecked")312ChronoZonedDateTime<D> end = (ChronoZonedDateTime<D>) getChronology().zonedDateTime(endExclusive);313if (unit instanceof ChronoUnit) {314end = end.withZoneSameInstant(offset);315return dateTime.until(end.toLocalDateTime(), unit);316}317Objects.requireNonNull(unit, "unit");318return unit.between(this, end);319}320321//-----------------------------------------------------------------------322/**323* Writes the ChronoZonedDateTime using a324* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.325* @serialData326* <pre>327* out.writeByte(3); // identifies a ChronoZonedDateTime328* out.writeObject(toLocalDateTime());329* out.writeObject(getOffset());330* out.writeObject(getZone());331* </pre>332*333* @return the instance of {@code Ser}, not null334*/335private Object writeReplace() {336return new Ser(Ser.CHRONO_ZONE_DATE_TIME_TYPE, this);337}338339/**340* Defend against malicious streams.341*342* @param s the stream to read343* @throws InvalidObjectException always344*/345private void readObject(ObjectInputStream s) throws InvalidObjectException {346throw new InvalidObjectException("Deserialization via serialization delegate");347}348349void writeExternal(ObjectOutput out) throws IOException {350out.writeObject(dateTime);351out.writeObject(offset);352out.writeObject(zone);353}354355static ChronoZonedDateTime<?> readExternal(ObjectInput in) throws IOException, ClassNotFoundException {356ChronoLocalDateTime<?> dateTime = (ChronoLocalDateTime<?>) in.readObject();357ZoneOffset offset = (ZoneOffset) in.readObject();358ZoneId zone = (ZoneId) in.readObject();359return dateTime.atZone(offset).withZoneSameLocal(zone);360// TODO: ZDT uses ofLenient()361}362363//-------------------------------------------------------------------------364@Override365public boolean equals(Object obj) {366if (this == obj) {367return true;368}369if (obj instanceof ChronoZonedDateTime) {370return compareTo((ChronoZonedDateTime<?>) obj) == 0;371}372return false;373}374375@Override376public int hashCode() {377return toLocalDateTime().hashCode() ^ getOffset().hashCode() ^ Integer.rotateLeft(getZone().hashCode(), 3);378}379380@Override381public String toString() {382String str = toLocalDateTime().toString() + getOffset().toString();383if (getOffset() != getZone()) {384str += '[' + getZone().toString() + ']';385}386return str;387}388389390}391392393