Path: blob/master/src/java.base/share/classes/java/time/chrono/ChronoLocalDateTimeImpl.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) 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.EPOCH_DAY;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.LocalTime;72import java.time.ZoneId;73import java.time.temporal.ChronoField;74import java.time.temporal.ChronoUnit;75import java.time.temporal.Temporal;76import java.time.temporal.TemporalAdjuster;77import java.time.temporal.TemporalField;78import java.time.temporal.TemporalUnit;79import java.time.temporal.ValueRange;80import java.util.Objects;8182/**83* A date-time without a time-zone for the calendar neutral API.84* <p>85* {@code ChronoLocalDateTime} is an immutable date-time object that represents a date-time, often86* viewed as year-month-day-hour-minute-second. This object can also access other87* fields such as day-of-year, day-of-week and week-of-year.88* <p>89* This class stores all date and time fields, to a precision of nanoseconds.90* It does not store or represent a time-zone. For example, the value91* "2nd October 2007 at 13:45.30.123456789" can be stored in an {@code ChronoLocalDateTime}.92*93* @implSpec94* This class is immutable and thread-safe.95* @serial96* @param <D> the concrete type for the date of this date-time97* @since 1.898*/99final class ChronoLocalDateTimeImpl<D extends ChronoLocalDate>100implements ChronoLocalDateTime<D>, Temporal, TemporalAdjuster, Serializable {101102/**103* Serialization version.104*/105@java.io.Serial106private static final long serialVersionUID = 4556003607393004514L;107/**108* Hours per day.109*/110static final int HOURS_PER_DAY = 24;111/**112* Minutes per hour.113*/114static final int MINUTES_PER_HOUR = 60;115/**116* Minutes per day.117*/118static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY;119/**120* Seconds per minute.121*/122static final int SECONDS_PER_MINUTE = 60;123/**124* Seconds per hour.125*/126static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;127/**128* Seconds per day.129*/130static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;131/**132* Milliseconds per day.133*/134static final long MILLIS_PER_DAY = SECONDS_PER_DAY * 1000L;135/**136* Microseconds per day.137*/138static final long MICROS_PER_DAY = SECONDS_PER_DAY * 1000_000L;139/**140* Nanos per second.141*/142static final long NANOS_PER_SECOND = 1000_000_000L;143/**144* Nanos per minute.145*/146static final long NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE;147/**148* Nanos per hour.149*/150static final long NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR;151/**152* Nanos per day.153*/154static final long NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;155156/**157* The date part.158*/159private final transient D date;160/**161* The time part.162*/163private final transient LocalTime time;164165//-----------------------------------------------------------------------166/**167* Obtains an instance of {@code ChronoLocalDateTime} from a date and time.168*169* @param date the local date, not null170* @param time the local time, not null171* @return the local date-time, not null172*/173static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> of(R date, LocalTime time) {174return new ChronoLocalDateTimeImpl<>(date, time);175}176177/**178* Casts the {@code Temporal} to {@code ChronoLocalDateTime} ensuring it bas the specified chronology.179*180* @param chrono the chronology to check for, not null181* @param temporal a date-time to cast, not null182* @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null183* @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl184* or the chronology is not equal this Chronology185*/186static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) {187@SuppressWarnings("unchecked")188ChronoLocalDateTimeImpl<R> other = (ChronoLocalDateTimeImpl<R>) temporal;189if (chrono.equals(other.getChronology()) == false) {190throw new ClassCastException("Chronology mismatch, required: " + chrono.getId()191+ ", actual: " + other.getChronology().getId());192}193return other;194}195196/**197* Constructor.198*199* @param date the date part of the date-time, not null200* @param time the time part of the date-time, not null201*/202private ChronoLocalDateTimeImpl(D date, LocalTime time) {203Objects.requireNonNull(date, "date");204Objects.requireNonNull(time, "time");205this.date = date;206this.time = time;207}208209/**210* Returns a copy of this date-time with the new date and time, checking211* to see if a new object is in fact required.212*213* @param newDate the date of the new date-time, not null214* @param newTime the time of the new date-time, not null215* @return the date-time, not null216*/217private ChronoLocalDateTimeImpl<D> with(Temporal newDate, LocalTime newTime) {218if (date == newDate && time == newTime) {219return this;220}221// Validate that the new Temporal is a ChronoLocalDate (and not something else)222D cd = ChronoLocalDateImpl.ensureValid(date.getChronology(), newDate);223return new ChronoLocalDateTimeImpl<>(cd, newTime);224}225226//-----------------------------------------------------------------------227@Override228public D toLocalDate() {229return date;230}231232@Override233public LocalTime toLocalTime() {234return time;235}236237//-----------------------------------------------------------------------238@Override239public boolean isSupported(TemporalField field) {240if (field instanceof ChronoField chronoField) {241return chronoField.isDateBased() || chronoField.isTimeBased();242}243return field != null && field.isSupportedBy(this);244}245246@Override247public ValueRange range(TemporalField field) {248if (field instanceof ChronoField chronoField) {249return (chronoField.isTimeBased() ? time.range(field) : date.range(field));250}251return field.rangeRefinedBy(this);252}253254@Override255public int get(TemporalField field) {256if (field instanceof ChronoField chronoField) {257return (chronoField.isTimeBased() ? time.get(field) : date.get(field));258}259return range(field).checkValidIntValue(getLong(field), field);260}261262@Override263public long getLong(TemporalField field) {264if (field instanceof ChronoField chronoField) {265return (chronoField.isTimeBased() ? time.getLong(field) : date.getLong(field));266}267return field.getFrom(this);268}269270//-----------------------------------------------------------------------271@SuppressWarnings("unchecked")272@Override273public ChronoLocalDateTimeImpl<D> with(TemporalAdjuster adjuster) {274if (adjuster instanceof ChronoLocalDate) {275// The Chronology is checked in with(date,time)276return with((ChronoLocalDate) adjuster, time);277} else if (adjuster instanceof LocalTime) {278return with(date, (LocalTime) adjuster);279} else if (adjuster instanceof ChronoLocalDateTimeImpl) {280return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), (ChronoLocalDateTimeImpl<?>) adjuster);281}282return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), (ChronoLocalDateTimeImpl<?>) adjuster.adjustInto(this));283}284285@Override286public ChronoLocalDateTimeImpl<D> with(TemporalField field, long newValue) {287if (field instanceof ChronoField chronoField) {288if (chronoField.isTimeBased()) {289return with(date, time.with(field, newValue));290} else {291return with(date.with(field, newValue), time);292}293}294return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), field.adjustInto(this, newValue));295}296297//-----------------------------------------------------------------------298@Override299public ChronoLocalDateTimeImpl<D> plus(long amountToAdd, TemporalUnit unit) {300if (unit instanceof ChronoUnit chronoUnit) {301switch (chronoUnit) {302case NANOS: return plusNanos(amountToAdd);303case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);304case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000000);305case SECONDS: return plusSeconds(amountToAdd);306case MINUTES: return plusMinutes(amountToAdd);307case HOURS: return plusHours(amountToAdd);308case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)309}310return with(date.plus(amountToAdd, unit), time);311}312return ChronoLocalDateTimeImpl.ensureValid(date.getChronology(), unit.addTo(this, amountToAdd));313}314315private ChronoLocalDateTimeImpl<D> plusDays(long days) {316return with(date.plus(days, ChronoUnit.DAYS), time);317}318319private ChronoLocalDateTimeImpl<D> plusHours(long hours) {320return plusWithOverflow(date, hours, 0, 0, 0);321}322323private ChronoLocalDateTimeImpl<D> plusMinutes(long minutes) {324return plusWithOverflow(date, 0, minutes, 0, 0);325}326327ChronoLocalDateTimeImpl<D> plusSeconds(long seconds) {328return plusWithOverflow(date, 0, 0, seconds, 0);329}330331private ChronoLocalDateTimeImpl<D> plusNanos(long nanos) {332return plusWithOverflow(date, 0, 0, 0, nanos);333}334335//-----------------------------------------------------------------------336private ChronoLocalDateTimeImpl<D> plusWithOverflow(D newDate, long hours, long minutes, long seconds, long nanos) {337// 9223372036854775808 long, 2147483648 int338if ((hours | minutes | seconds | nanos) == 0) {339return with(newDate, time);340}341long totDays = nanos / NANOS_PER_DAY + // max/24*60*60*1B342seconds / SECONDS_PER_DAY + // max/24*60*60343minutes / MINUTES_PER_DAY + // max/24*60344hours / HOURS_PER_DAY; // max/24345long totNanos = nanos % NANOS_PER_DAY + // max 86400000000000346(seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND + // max 86400000000000347(minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE + // max 86400000000000348(hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 86400000000000349long curNoD = time.toNanoOfDay(); // max 86400000000000350totNanos = totNanos + curNoD; // total 432000000000000351totDays += Math.floorDiv(totNanos, NANOS_PER_DAY);352long newNoD = Math.floorMod(totNanos, NANOS_PER_DAY);353LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD));354return with(newDate.plus(totDays, ChronoUnit.DAYS), newTime);355}356357//-----------------------------------------------------------------------358@Override359public ChronoZonedDateTime<D> atZone(ZoneId zone) {360return ChronoZonedDateTimeImpl.ofBest(this, zone, null);361}362363//-----------------------------------------------------------------------364@Override365public long until(Temporal endExclusive, TemporalUnit unit) {366Objects.requireNonNull(endExclusive, "endExclusive");367@SuppressWarnings("unchecked")368ChronoLocalDateTime<D> end = (ChronoLocalDateTime<D>) getChronology().localDateTime(endExclusive);369if (unit instanceof ChronoUnit chronoUnit) {370if (unit.isTimeBased()) {371long amount = end.getLong(EPOCH_DAY) - date.getLong(EPOCH_DAY);372switch (chronoUnit) {373case NANOS: amount = Math.multiplyExact(amount, NANOS_PER_DAY); break;374case MICROS: amount = Math.multiplyExact(amount, MICROS_PER_DAY); break;375case MILLIS: amount = Math.multiplyExact(amount, MILLIS_PER_DAY); break;376case SECONDS: amount = Math.multiplyExact(amount, SECONDS_PER_DAY); break;377case MINUTES: amount = Math.multiplyExact(amount, MINUTES_PER_DAY); break;378case HOURS: amount = Math.multiplyExact(amount, HOURS_PER_DAY); break;379case HALF_DAYS: amount = Math.multiplyExact(amount, 2); break;380}381return Math.addExact(amount, time.until(end.toLocalTime(), unit));382}383ChronoLocalDate endDate = end.toLocalDate();384if (end.toLocalTime().isBefore(time)) {385endDate = endDate.minus(1, ChronoUnit.DAYS);386}387return date.until(endDate, unit);388}389Objects.requireNonNull(unit, "unit");390return unit.between(this, end);391}392393//-----------------------------------------------------------------------394/**395* Writes the ChronoLocalDateTime using a396* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.397* @serialData398* <pre>399* out.writeByte(2); // identifies a ChronoLocalDateTime400* out.writeObject(toLocalDate());401* out.writeObject(toLocalTime());402* </pre>403*404* @return the instance of {@code Ser}, not null405*/406@java.io.Serial407private Object writeReplace() {408return new Ser(Ser.CHRONO_LOCAL_DATE_TIME_TYPE, this);409}410411/**412* Defend against malicious streams.413*414* @param s the stream to read415* @throws InvalidObjectException always416*/417@java.io.Serial418private void readObject(ObjectInputStream s) throws InvalidObjectException {419throw new InvalidObjectException("Deserialization via serialization delegate");420}421422void writeExternal(ObjectOutput out) throws IOException {423out.writeObject(date);424out.writeObject(time);425}426427static ChronoLocalDateTime<?> readExternal(ObjectInput in) throws IOException, ClassNotFoundException {428ChronoLocalDate date = (ChronoLocalDate) in.readObject();429LocalTime time = (LocalTime) in.readObject();430return date.atTime(time);431}432433//-----------------------------------------------------------------------434@Override435public boolean equals(Object obj) {436if (this == obj) {437return true;438}439if (obj instanceof ChronoLocalDateTime) {440return compareTo((ChronoLocalDateTime<?>) obj) == 0;441}442return false;443}444445@Override446public int hashCode() {447return toLocalDate().hashCode() ^ toLocalTime().hashCode();448}449450@Override451public String toString() {452return toLocalDate().toString() + 'T' + toLocalTime().toString();453}454455}456457458