Path: blob/master/src/java.base/share/classes/java/time/chrono/ChronoZonedDateTimeImpl.java
41159 views
/*1* Copyright (c) 2012, 2019, 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*/109@java.io.Serial110private static final long serialVersionUID = -5261813987200935591L;111112/**113* The local date-time.114*/115private final transient ChronoLocalDateTimeImpl<D> dateTime;116/**117* The zone offset.118*/119private final transient ZoneOffset offset;120/**121* The zone ID.122*/123private final transient ZoneId zone;124125//-----------------------------------------------------------------------126/**127* Obtains an instance from a local date-time using the preferred offset if possible.128*129* @param localDateTime the local date-time, not null130* @param zone the zone identifier, not null131* @param preferredOffset the zone offset, null if no preference132* @return the zoned date-time, not null133*/134static <R extends ChronoLocalDate> ChronoZonedDateTime<R> ofBest(135ChronoLocalDateTimeImpl<R> localDateTime, ZoneId zone, ZoneOffset preferredOffset) {136Objects.requireNonNull(localDateTime, "localDateTime");137Objects.requireNonNull(zone, "zone");138if (zone instanceof ZoneOffset) {139return new ChronoZonedDateTimeImpl<>(localDateTime, (ZoneOffset) zone, zone);140}141ZoneRules rules = zone.getRules();142LocalDateTime isoLDT = LocalDateTime.from(localDateTime);143List<ZoneOffset> validOffsets = rules.getValidOffsets(isoLDT);144ZoneOffset offset;145if (validOffsets.size() == 1) {146offset = validOffsets.get(0);147} else if (validOffsets.size() == 0) {148ZoneOffsetTransition trans = rules.getTransition(isoLDT);149localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());150offset = trans.getOffsetAfter();151} else {152if (preferredOffset != null && validOffsets.contains(preferredOffset)) {153offset = preferredOffset;154} else {155offset = validOffsets.get(0);156}157}158Objects.requireNonNull(offset, "offset"); // protect against bad ZoneRules159return new ChronoZonedDateTimeImpl<>(localDateTime, offset, zone);160}161162/**163* Obtains an instance from an instant using the specified time-zone.164*165* @param chrono the chronology, not null166* @param instant the instant, not null167* @param zone the zone identifier, not null168* @return the zoned date-time, not null169*/170static ChronoZonedDateTimeImpl<?> ofInstant(Chronology chrono, Instant instant, ZoneId zone) {171ZoneRules rules = zone.getRules();172ZoneOffset offset = rules.getOffset(instant);173Objects.requireNonNull(offset, "offset"); // protect against bad ZoneRules174LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);175ChronoLocalDateTimeImpl<?> cldt = (ChronoLocalDateTimeImpl<?>)chrono.localDateTime(ldt);176return new ChronoZonedDateTimeImpl<>(cldt, offset, zone);177}178179/**180* Obtains an instance from an {@code Instant}.181*182* @param instant the instant to create the date-time from, not null183* @param zone the time-zone to use, validated not null184* @return the zoned date-time, validated not null185*/186@SuppressWarnings("unchecked")187private ChronoZonedDateTimeImpl<D> create(Instant instant, ZoneId zone) {188return (ChronoZonedDateTimeImpl<D>)ofInstant(getChronology(), instant, zone);189}190191/**192* Casts the {@code Temporal} to {@code ChronoZonedDateTimeImpl} ensuring it bas the specified chronology.193*194* @param chrono the chronology to check for, not null195* @param temporal a date-time to cast, not null196* @return the date-time checked and cast to {@code ChronoZonedDateTimeImpl}, not null197* @throws ClassCastException if the date-time cannot be cast to ChronoZonedDateTimeImpl198* or the chronology is not equal this Chronology199*/200static <R extends ChronoLocalDate> ChronoZonedDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) {201@SuppressWarnings("unchecked")202ChronoZonedDateTimeImpl<R> other = (ChronoZonedDateTimeImpl<R>) temporal;203if (chrono.equals(other.getChronology()) == false) {204throw new ClassCastException("Chronology mismatch, required: " + chrono.getId()205+ ", actual: " + other.getChronology().getId());206}207return other;208}209210//-----------------------------------------------------------------------211/**212* Constructor.213*214* @param dateTime the date-time, not null215* @param offset the zone offset, not null216* @param zone the zone ID, not null217*/218private ChronoZonedDateTimeImpl(ChronoLocalDateTimeImpl<D> dateTime, ZoneOffset offset, ZoneId zone) {219this.dateTime = Objects.requireNonNull(dateTime, "dateTime");220this.offset = Objects.requireNonNull(offset, "offset");221this.zone = Objects.requireNonNull(zone, "zone");222}223224//-----------------------------------------------------------------------225@Override226public ZoneOffset getOffset() {227return offset;228}229230@Override231public ChronoZonedDateTime<D> withEarlierOffsetAtOverlap() {232ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));233if (trans != null && trans.isOverlap()) {234ZoneOffset earlierOffset = trans.getOffsetBefore();235if (earlierOffset.equals(offset) == false) {236return new ChronoZonedDateTimeImpl<>(dateTime, earlierOffset, zone);237}238}239return this;240}241242@Override243public ChronoZonedDateTime<D> withLaterOffsetAtOverlap() {244ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));245if (trans != null) {246ZoneOffset offset = trans.getOffsetAfter();247if (offset.equals(getOffset()) == false) {248return new ChronoZonedDateTimeImpl<>(dateTime, offset, zone);249}250}251return this;252}253254//-----------------------------------------------------------------------255@Override256public ChronoLocalDateTime<D> toLocalDateTime() {257return dateTime;258}259260@Override261public ZoneId getZone() {262return zone;263}264265@Override266public ChronoZonedDateTime<D> withZoneSameLocal(ZoneId zone) {267return ofBest(dateTime, zone, offset);268}269270@Override271public ChronoZonedDateTime<D> withZoneSameInstant(ZoneId zone) {272Objects.requireNonNull(zone, "zone");273return this.zone.equals(zone) ? this : create(dateTime.toInstant(offset), zone);274}275276//-----------------------------------------------------------------------277@Override278public boolean isSupported(TemporalField field) {279return field instanceof ChronoField || (field != null && field.isSupportedBy(this));280}281282//-----------------------------------------------------------------------283@Override284public ChronoZonedDateTime<D> with(TemporalField field, long newValue) {285if (field instanceof ChronoField chronoField) {286switch (chronoField) {287case INSTANT_SECONDS: return plus(newValue - toEpochSecond(), SECONDS);288case OFFSET_SECONDS: {289ZoneOffset offset = ZoneOffset.ofTotalSeconds(chronoField.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="{@docRoot}/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*/335@java.io.Serial336private Object writeReplace() {337return new Ser(Ser.CHRONO_ZONE_DATE_TIME_TYPE, this);338}339340/**341* Defend against malicious streams.342*343* @param s the stream to read344* @throws InvalidObjectException always345*/346@java.io.Serial347private void readObject(ObjectInputStream s) throws InvalidObjectException {348throw new InvalidObjectException("Deserialization via serialization delegate");349}350351void writeExternal(ObjectOutput out) throws IOException {352out.writeObject(dateTime);353out.writeObject(offset);354out.writeObject(zone);355}356357static ChronoZonedDateTime<?> readExternal(ObjectInput in) throws IOException, ClassNotFoundException {358ChronoLocalDateTime<?> dateTime = (ChronoLocalDateTime<?>) in.readObject();359ZoneOffset offset = (ZoneOffset) in.readObject();360ZoneId zone = (ZoneId) in.readObject();361return dateTime.atZone(offset).withZoneSameLocal(zone);362// TODO: ZDT uses ofLenient()363}364365//-------------------------------------------------------------------------366@Override367public boolean equals(Object obj) {368if (this == obj) {369return true;370}371if (obj instanceof ChronoZonedDateTime) {372return compareTo((ChronoZonedDateTime<?>) obj) == 0;373}374return false;375}376377@Override378public int hashCode() {379return toLocalDateTime().hashCode() ^ getOffset().hashCode() ^ Integer.rotateLeft(getZone().hashCode(), 3);380}381382@Override383public String toString() {384String str = toLocalDateTime().toString() + getOffset().toString();385if (getOffset() != getZone()) {386str += '[' + getZone().toString() + ']';387}388return str;389}390391392}393394395