Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/ChronoZonedDateTime.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) 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.ChronoField.INSTANT_SECONDS;64import static java.time.temporal.ChronoField.OFFSET_SECONDS;65import static java.time.temporal.ChronoUnit.FOREVER;66import static java.time.temporal.ChronoUnit.NANOS;6768import java.time.DateTimeException;69import java.time.Instant;70import java.time.LocalTime;71import java.time.ZoneId;72import java.time.ZoneOffset;73import java.time.ZonedDateTime;74import java.time.format.DateTimeFormatter;75import java.time.temporal.ChronoField;76import java.time.temporal.ChronoUnit;77import java.time.temporal.Temporal;78import java.time.temporal.TemporalAccessor;79import java.time.temporal.TemporalAdjuster;80import java.time.temporal.TemporalAmount;81import java.time.temporal.TemporalField;82import java.time.temporal.TemporalQueries;83import java.time.temporal.TemporalQuery;84import java.time.temporal.TemporalUnit;85import java.time.temporal.UnsupportedTemporalTypeException;86import java.time.temporal.ValueRange;87import java.util.Comparator;88import java.util.Objects;8990/**91* A date-time with a time-zone in an arbitrary chronology,92* intended for advanced globalization use cases.93* <p>94* <b>Most applications should declare method signatures, fields and variables95* as {@link ZonedDateTime}, not this interface.</b>96* <p>97* A {@code ChronoZonedDateTime} is the abstract representation of an offset date-time98* where the {@code Chronology chronology}, or calendar system, is pluggable.99* The date-time is defined in terms of fields expressed by {@link TemporalField},100* where most common implementations are defined in {@link ChronoField}.101* The chronology defines how the calendar system operates and the meaning of102* the standard fields.103*104* <h3>When to use this interface</h3>105* The design of the API encourages the use of {@code ZonedDateTime} rather than this106* interface, even in the case where the application needs to deal with multiple107* calendar systems. The rationale for this is explored in detail in {@link ChronoLocalDate}.108* <p>109* Ensure that the discussion in {@code ChronoLocalDate} has been read and understood110* before using this interface.111*112* @implSpec113* This interface must be implemented with care to ensure other classes operate correctly.114* All implementations that can be instantiated must be final, immutable and thread-safe.115* Subclasses should be Serializable wherever possible.116*117* @param <D> the concrete type for the date of this date-time118* @since 1.8119*/120public interface ChronoZonedDateTime<D extends ChronoLocalDate>121extends Temporal, Comparable<ChronoZonedDateTime<?>> {122123/**124* Gets a comparator that compares {@code ChronoZonedDateTime} in125* time-line order ignoring the chronology.126* <p>127* This comparator differs from the comparison in {@link #compareTo} in that it128* only compares the underlying instant and not the chronology.129* This allows dates in different calendar systems to be compared based130* on the position of the date-time on the instant time-line.131* The underlying comparison is equivalent to comparing the epoch-second and nano-of-second.132*133* @return a comparator that compares in time-line order ignoring the chronology134* @see #isAfter135* @see #isBefore136* @see #isEqual137*/138static Comparator<ChronoZonedDateTime<?>> timeLineOrder() {139return AbstractChronology.INSTANT_ORDER;140}141142//-----------------------------------------------------------------------143/**144* Obtains an instance of {@code ChronoZonedDateTime} from a temporal object.145* <p>146* This creates a zoned date-time based on the specified temporal.147* A {@code TemporalAccessor} represents an arbitrary set of date and time information,148* which this factory converts to an instance of {@code ChronoZonedDateTime}.149* <p>150* The conversion extracts and combines the chronology, date, time and zone151* from the temporal object. The behavior is equivalent to using152* {@link Chronology#zonedDateTime(TemporalAccessor)} with the extracted chronology.153* Implementations are permitted to perform optimizations such as accessing154* those fields that are equivalent to the relevant objects.155* <p>156* This method matches the signature of the functional interface {@link TemporalQuery}157* allowing it to be used as a query via method reference, {@code ChronoZonedDateTime::from}.158*159* @param temporal the temporal object to convert, not null160* @return the date-time, not null161* @throws DateTimeException if unable to convert to a {@code ChronoZonedDateTime}162* @see Chronology#zonedDateTime(TemporalAccessor)163*/164static ChronoZonedDateTime<?> from(TemporalAccessor temporal) {165if (temporal instanceof ChronoZonedDateTime) {166return (ChronoZonedDateTime<?>) temporal;167}168Objects.requireNonNull(temporal, "temporal");169Chronology chrono = temporal.query(TemporalQueries.chronology());170if (chrono == null) {171throw new DateTimeException("Unable to obtain ChronoZonedDateTime from TemporalAccessor: " + temporal.getClass());172}173return chrono.zonedDateTime(temporal);174}175176//-----------------------------------------------------------------------177@Override178default ValueRange range(TemporalField field) {179if (field instanceof ChronoField) {180if (field == INSTANT_SECONDS || field == OFFSET_SECONDS) {181return field.range();182}183return toLocalDateTime().range(field);184}185return field.rangeRefinedBy(this);186}187188@Override189default int get(TemporalField field) {190if (field instanceof ChronoField) {191switch ((ChronoField) field) {192case INSTANT_SECONDS:193throw new UnsupportedTemporalTypeException("Invalid field 'InstantSeconds' for get() method, use getLong() instead");194case OFFSET_SECONDS:195return getOffset().getTotalSeconds();196}197return toLocalDateTime().get(field);198}199return Temporal.super.get(field);200}201202@Override203default long getLong(TemporalField field) {204if (field instanceof ChronoField) {205switch ((ChronoField) field) {206case INSTANT_SECONDS: return toEpochSecond();207case OFFSET_SECONDS: return getOffset().getTotalSeconds();208}209return toLocalDateTime().getLong(field);210}211return field.getFrom(this);212}213214/**215* Gets the local date part of this date-time.216* <p>217* This returns a local date with the same year, month and day218* as this date-time.219*220* @return the date part of this date-time, not null221*/222default D toLocalDate() {223return toLocalDateTime().toLocalDate();224}225226/**227* Gets the local time part of this date-time.228* <p>229* This returns a local time with the same hour, minute, second and230* nanosecond as this date-time.231*232* @return the time part of this date-time, not null233*/234default LocalTime toLocalTime() {235return toLocalDateTime().toLocalTime();236}237238/**239* Gets the local date-time part of this date-time.240* <p>241* This returns a local date with the same year, month and day242* as this date-time.243*244* @return the local date-time part of this date-time, not null245*/246ChronoLocalDateTime<D> toLocalDateTime();247248/**249* Gets the chronology of this date-time.250* <p>251* The {@code Chronology} represents the calendar system in use.252* The era and other fields in {@link ChronoField} are defined by the chronology.253*254* @return the chronology, not null255*/256default Chronology getChronology() {257return toLocalDate().getChronology();258}259260/**261* Gets the zone offset, such as '+01:00'.262* <p>263* This is the offset of the local date-time from UTC/Greenwich.264*265* @return the zone offset, not null266*/267ZoneOffset getOffset();268269/**270* Gets the zone ID, such as 'Europe/Paris'.271* <p>272* This returns the stored time-zone id used to determine the time-zone rules.273*274* @return the zone ID, not null275*/276ZoneId getZone();277278//-----------------------------------------------------------------------279/**280* Returns a copy of this date-time changing the zone offset to the281* earlier of the two valid offsets at a local time-line overlap.282* <p>283* This method only has any effect when the local time-line overlaps, such as284* at an autumn daylight savings cutover. In this scenario, there are two285* valid offsets for the local date-time. Calling this method will return286* a zoned date-time with the earlier of the two selected.287* <p>288* If this method is called when it is not an overlap, {@code this}289* is returned.290* <p>291* This instance is immutable and unaffected by this method call.292*293* @return a {@code ChronoZonedDateTime} based on this date-time with the earlier offset, not null294* @throws DateTimeException if no rules can be found for the zone295* @throws DateTimeException if no rules are valid for this date-time296*/297ChronoZonedDateTime<D> withEarlierOffsetAtOverlap();298299/**300* Returns a copy of this date-time changing the zone offset to the301* later of the two valid offsets at a local time-line overlap.302* <p>303* This method only has any effect when the local time-line overlaps, such as304* at an autumn daylight savings cutover. In this scenario, there are two305* valid offsets for the local date-time. Calling this method will return306* a zoned date-time with the later of the two selected.307* <p>308* If this method is called when it is not an overlap, {@code this}309* is returned.310* <p>311* This instance is immutable and unaffected by this method call.312*313* @return a {@code ChronoZonedDateTime} based on this date-time with the later offset, not null314* @throws DateTimeException if no rules can be found for the zone315* @throws DateTimeException if no rules are valid for this date-time316*/317ChronoZonedDateTime<D> withLaterOffsetAtOverlap();318319/**320* Returns a copy of this date-time with a different time-zone,321* retaining the local date-time if possible.322* <p>323* This method changes the time-zone and retains the local date-time.324* The local date-time is only changed if it is invalid for the new zone.325* <p>326* To change the zone and adjust the local date-time,327* use {@link #withZoneSameInstant(ZoneId)}.328* <p>329* This instance is immutable and unaffected by this method call.330*331* @param zone the time-zone to change to, not null332* @return a {@code ChronoZonedDateTime} based on this date-time with the requested zone, not null333*/334ChronoZonedDateTime<D> withZoneSameLocal(ZoneId zone);335336/**337* Returns a copy of this date-time with a different time-zone,338* retaining the instant.339* <p>340* This method changes the time-zone and retains the instant.341* This normally results in a change to the local date-time.342* <p>343* This method is based on retaining the same instant, thus gaps and overlaps344* in the local time-line have no effect on the result.345* <p>346* To change the offset while keeping the local time,347* use {@link #withZoneSameLocal(ZoneId)}.348*349* @param zone the time-zone to change to, not null350* @return a {@code ChronoZonedDateTime} based on this date-time with the requested zone, not null351* @throws DateTimeException if the result exceeds the supported date range352*/353ChronoZonedDateTime<D> withZoneSameInstant(ZoneId zone);354355/**356* Checks if the specified field is supported.357* <p>358* This checks if the specified field can be queried on this date-time.359* If false, then calling the {@link #range(TemporalField) range},360* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}361* methods will throw an exception.362* <p>363* The set of supported fields is defined by the chronology and normally includes364* all {@code ChronoField} fields.365* <p>366* If the field is not a {@code ChronoField}, then the result of this method367* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}368* passing {@code this} as the argument.369* Whether the field is supported is determined by the field.370*371* @param field the field to check, null returns false372* @return true if the field can be queried, false if not373*/374@Override375boolean isSupported(TemporalField field);376377/**378* Checks if the specified unit is supported.379* <p>380* This checks if the specified unit can be added to or subtracted from this date-time.381* If false, then calling the {@link #plus(long, TemporalUnit)} and382* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.383* <p>384* The set of supported units is defined by the chronology and normally includes385* all {@code ChronoUnit} units except {@code FOREVER}.386* <p>387* If the unit is not a {@code ChronoUnit}, then the result of this method388* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}389* passing {@code this} as the argument.390* Whether the unit is supported is determined by the unit.391*392* @param unit the unit to check, null returns false393* @return true if the unit can be added/subtracted, false if not394*/395@Override396default boolean isSupported(TemporalUnit unit) {397if (unit instanceof ChronoUnit) {398return unit != FOREVER;399}400return unit != null && unit.isSupportedBy(this);401}402403//-----------------------------------------------------------------------404// override for covariant return type405/**406* {@inheritDoc}407* @throws DateTimeException {@inheritDoc}408* @throws ArithmeticException {@inheritDoc}409*/410@Override411default ChronoZonedDateTime<D> with(TemporalAdjuster adjuster) {412return ChronoZonedDateTimeImpl.ensureValid(getChronology(), Temporal.super.with(adjuster));413}414415/**416* {@inheritDoc}417* @throws DateTimeException {@inheritDoc}418* @throws ArithmeticException {@inheritDoc}419*/420@Override421ChronoZonedDateTime<D> with(TemporalField field, long newValue);422423/**424* {@inheritDoc}425* @throws DateTimeException {@inheritDoc}426* @throws ArithmeticException {@inheritDoc}427*/428@Override429default ChronoZonedDateTime<D> plus(TemporalAmount amount) {430return ChronoZonedDateTimeImpl.ensureValid(getChronology(), Temporal.super.plus(amount));431}432433/**434* {@inheritDoc}435* @throws DateTimeException {@inheritDoc}436* @throws ArithmeticException {@inheritDoc}437*/438@Override439ChronoZonedDateTime<D> plus(long amountToAdd, TemporalUnit unit);440441/**442* {@inheritDoc}443* @throws DateTimeException {@inheritDoc}444* @throws ArithmeticException {@inheritDoc}445*/446@Override447default ChronoZonedDateTime<D> minus(TemporalAmount amount) {448return ChronoZonedDateTimeImpl.ensureValid(getChronology(), Temporal.super.minus(amount));449}450451/**452* {@inheritDoc}453* @throws DateTimeException {@inheritDoc}454* @throws ArithmeticException {@inheritDoc}455*/456@Override457default ChronoZonedDateTime<D> minus(long amountToSubtract, TemporalUnit unit) {458return ChronoZonedDateTimeImpl.ensureValid(getChronology(), Temporal.super.minus(amountToSubtract, unit));459}460461//-----------------------------------------------------------------------462/**463* Queries this date-time using the specified query.464* <p>465* This queries this date-time using the specified query strategy object.466* The {@code TemporalQuery} object defines the logic to be used to467* obtain the result. Read the documentation of the query to understand468* what the result of this method will be.469* <p>470* The result of this method is obtained by invoking the471* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the472* specified query passing {@code this} as the argument.473*474* @param <R> the type of the result475* @param query the query to invoke, not null476* @return the query result, null may be returned (defined by the query)477* @throws DateTimeException if unable to query (defined by the query)478* @throws ArithmeticException if numeric overflow occurs (defined by the query)479*/480@SuppressWarnings("unchecked")481@Override482default <R> R query(TemporalQuery<R> query) {483if (query == TemporalQueries.zone() || query == TemporalQueries.zoneId()) {484return (R) getZone();485} else if (query == TemporalQueries.offset()) {486return (R) getOffset();487} else if (query == TemporalQueries.localTime()) {488return (R) toLocalTime();489} else if (query == TemporalQueries.chronology()) {490return (R) getChronology();491} else if (query == TemporalQueries.precision()) {492return (R) NANOS;493}494// inline TemporalAccessor.super.query(query) as an optimization495// non-JDK classes are not permitted to make this optimization496return query.queryFrom(this);497}498499/**500* Formats this date-time using the specified formatter.501* <p>502* This date-time will be passed to the formatter to produce a string.503* <p>504* The default implementation must behave as follows:505* <pre>506* return formatter.format(this);507* </pre>508*509* @param formatter the formatter to use, not null510* @return the formatted date-time string, not null511* @throws DateTimeException if an error occurs during printing512*/513default String format(DateTimeFormatter formatter) {514Objects.requireNonNull(formatter, "formatter");515return formatter.format(this);516}517518//-----------------------------------------------------------------------519/**520* Converts this date-time to an {@code Instant}.521* <p>522* This returns an {@code Instant} representing the same point on the523* time-line as this date-time. The calculation combines the524* {@linkplain #toLocalDateTime() local date-time} and525* {@linkplain #getOffset() offset}.526*527* @return an {@code Instant} representing the same instant, not null528*/529default Instant toInstant() {530return Instant.ofEpochSecond(toEpochSecond(), toLocalTime().getNano());531}532533/**534* Converts this date-time to the number of seconds from the epoch535* of 1970-01-01T00:00:00Z.536* <p>537* This uses the {@linkplain #toLocalDateTime() local date-time} and538* {@linkplain #getOffset() offset} to calculate the epoch-second value,539* which is the number of elapsed seconds from 1970-01-01T00:00:00Z.540* Instants on the time-line after the epoch are positive, earlier are negative.541*542* @return the number of seconds from the epoch of 1970-01-01T00:00:00Z543*/544default long toEpochSecond() {545long epochDay = toLocalDate().toEpochDay();546long secs = epochDay * 86400 + toLocalTime().toSecondOfDay();547secs -= getOffset().getTotalSeconds();548return secs;549}550551//-----------------------------------------------------------------------552/**553* Compares this date-time to another date-time, including the chronology.554* <p>555* The comparison is based first on the instant, then on the local date-time,556* then on the zone ID, then on the chronology.557* It is "consistent with equals", as defined by {@link Comparable}.558* <p>559* If all the date-time objects being compared are in the same chronology, then the560* additional chronology stage is not required.561* <p>562* This default implementation performs the comparison defined above.563*564* @param other the other date-time to compare to, not null565* @return the comparator value, negative if less, positive if greater566*/567@Override568default int compareTo(ChronoZonedDateTime<?> other) {569int cmp = Long.compare(toEpochSecond(), other.toEpochSecond());570if (cmp == 0) {571cmp = toLocalTime().getNano() - other.toLocalTime().getNano();572if (cmp == 0) {573cmp = toLocalDateTime().compareTo(other.toLocalDateTime());574if (cmp == 0) {575cmp = getZone().getId().compareTo(other.getZone().getId());576if (cmp == 0) {577cmp = getChronology().compareTo(other.getChronology());578}579}580}581}582return cmp;583}584585/**586* Checks if the instant of this date-time is before that of the specified date-time.587* <p>588* This method differs from the comparison in {@link #compareTo} in that it589* only compares the instant of the date-time. This is equivalent to using590* {@code dateTime1.toInstant().isBefore(dateTime2.toInstant());}.591* <p>592* This default implementation performs the comparison based on the epoch-second593* and nano-of-second.594*595* @param other the other date-time to compare to, not null596* @return true if this point is before the specified date-time597*/598default boolean isBefore(ChronoZonedDateTime<?> other) {599long thisEpochSec = toEpochSecond();600long otherEpochSec = other.toEpochSecond();601return thisEpochSec < otherEpochSec ||602(thisEpochSec == otherEpochSec && toLocalTime().getNano() < other.toLocalTime().getNano());603}604605/**606* Checks if the instant of this date-time is after that of the specified date-time.607* <p>608* This method differs from the comparison in {@link #compareTo} in that it609* only compares the instant of the date-time. This is equivalent to using610* {@code dateTime1.toInstant().isAfter(dateTime2.toInstant());}.611* <p>612* This default implementation performs the comparison based on the epoch-second613* and nano-of-second.614*615* @param other the other date-time to compare to, not null616* @return true if this is after the specified date-time617*/618default boolean isAfter(ChronoZonedDateTime<?> other) {619long thisEpochSec = toEpochSecond();620long otherEpochSec = other.toEpochSecond();621return thisEpochSec > otherEpochSec ||622(thisEpochSec == otherEpochSec && toLocalTime().getNano() > other.toLocalTime().getNano());623}624625/**626* Checks if the instant of this date-time is equal to that of the specified date-time.627* <p>628* This method differs from the comparison in {@link #compareTo} and {@link #equals}629* in that it only compares the instant of the date-time. This is equivalent to using630* {@code dateTime1.toInstant().equals(dateTime2.toInstant());}.631* <p>632* This default implementation performs the comparison based on the epoch-second633* and nano-of-second.634*635* @param other the other date-time to compare to, not null636* @return true if the instant equals the instant of the specified date-time637*/638default boolean isEqual(ChronoZonedDateTime<?> other) {639return toEpochSecond() == other.toEpochSecond() &&640toLocalTime().getNano() == other.toLocalTime().getNano();641}642643//-----------------------------------------------------------------------644/**645* Checks if this date-time is equal to another date-time.646* <p>647* The comparison is based on the offset date-time and the zone.648* To compare for the same instant on the time-line, use {@link #compareTo}.649* Only objects of type {@code ChronoZonedDateTime} are compared, other types return false.650*651* @param obj the object to check, null returns false652* @return true if this is equal to the other date-time653*/654@Override655boolean equals(Object obj);656657/**658* A hash code for this date-time.659*660* @return a suitable hash code661*/662@Override663int hashCode();664665//-----------------------------------------------------------------------666/**667* Outputs this date-time as a {@code String}.668* <p>669* The output will include the full zoned date-time.670*671* @return a string representation of this date-time, not null672*/673@Override674String toString();675676}677678679