# HG changeset patch # User rriggs # Date 1377859437 -3600 # Node ID dde564773845e4b38d39fecaee1df2d7c6f46e2e # Parent 1336a85b3d5231023b777c47d8c380ee44a0c300 8023763: Rename ChronoDateImpl Summary: Rename ChronoDateImpl to ChronoLocalDateImpl Reviewed-by: sherman Contributed-by: scolebourne@joda.org diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/ChronoDateImpl.java --- a/jdk/src/share/classes/java/time/chrono/ChronoDateImpl.java Thu Aug 29 20:38:46 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,455 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package java.time.chrono; - -import static java.time.temporal.ChronoField.DAY_OF_MONTH; -import static java.time.temporal.ChronoField.ERA; -import static java.time.temporal.ChronoField.MONTH_OF_YEAR; -import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; -import static java.time.temporal.ChronoField.YEAR_OF_ERA; - -import java.io.Serializable; -import java.time.DateTimeException; -import java.time.temporal.ChronoUnit; -import java.time.temporal.Temporal; -import java.time.temporal.TemporalAdjuster; -import java.time.temporal.TemporalAmount; -import java.time.temporal.TemporalField; -import java.time.temporal.TemporalUnit; -import java.time.temporal.UnsupportedTemporalTypeException; -import java.time.temporal.ValueRange; -import java.util.Objects; - -/** - * A date expressed in terms of a standard year-month-day calendar system. - *

- * This class is used by applications seeking to handle dates in non-ISO calendar systems. - * For example, the Japanese, Minguo, Thai Buddhist and others. - *

- * {@code ChronoLocalDate} is built on the generic concepts of year, month and day. - * The calendar system, represented by a {@link java.time.chrono.Chronology}, expresses the relationship between - * the fields and this class allows the resulting date to be manipulated. - *

- * Note that not all calendar systems are suitable for use with this class. - * For example, the Mayan calendar uses a system that bears no relation to years, months and days. - *

- * The API design encourages the use of {@code LocalDate} for the majority of the application. - * This includes code to read and write from a persistent data store, such as a database, - * and to send dates and times across a network. The {@code ChronoLocalDate} instance is then used - * at the user interface level to deal with localized input/output. - * - *

Example:

- *
- *        System.out.printf("Example()%n");
- *        // Enumerate the list of available calendars and print today for each
- *        Set<Chronology> chronos = Chronology.getAvailableChronologies();
- *        for (Chronology chrono : chronos) {
- *            ChronoLocalDate date = chrono.dateNow();
- *            System.out.printf("   %20s: %s%n", chrono.getID(), date.toString());
- *        }
- *
- *        // Print the Hijrah date and calendar
- *        ChronoLocalDate date = Chronology.of("Hijrah").dateNow();
- *        int day = date.get(ChronoField.DAY_OF_MONTH);
- *        int dow = date.get(ChronoField.DAY_OF_WEEK);
- *        int month = date.get(ChronoField.MONTH_OF_YEAR);
- *        int year = date.get(ChronoField.YEAR);
- *        System.out.printf("  Today is %s %s %d-%s-%d%n", date.getChronology().getID(),
- *                dow, day, month, year);
-
- *        // Print today's date and the last day of the year
- *        ChronoLocalDate now1 = Chronology.of("Hijrah").dateNow();
- *        ChronoLocalDate first = now1.with(ChronoField.DAY_OF_MONTH, 1)
- *                .with(ChronoField.MONTH_OF_YEAR, 1);
- *        ChronoLocalDate last = first.plus(1, ChronoUnit.YEARS)
- *                .minus(1, ChronoUnit.DAYS);
- *        System.out.printf("  Today is %s: start: %s; end: %s%n", last.getChronology().getID(),
- *                first, last);
- * 
- * - *

Adding Calendars

- *

The set of calendars is extensible by defining a subclass of {@link ChronoLocalDate} - * to represent a date instance and an implementation of {@code Chronology} - * to be the factory for the ChronoLocalDate subclass. - *

- *

To permit the discovery of the additional calendar types the implementation of - * {@code Chronology} must be registered as a Service implementing the {@code Chronology} interface - * in the {@code META-INF/Services} file as per the specification of {@link java.util.ServiceLoader}. - * The subclass must function according to the {@code Chronology} class description and must provide its - * {@link java.time.chrono.Chronology#getId() chronlogy ID} and {@link Chronology#getCalendarType() calendar type}.

- * - * @implSpec - * This abstract class must be implemented with care to ensure other classes operate correctly. - * All implementations that can be instantiated must be final, immutable and thread-safe. - * Subclasses should be Serializable wherever possible. - * - * @param the ChronoLocalDate of this date-time - * @since 1.8 - */ -abstract class ChronoDateImpl - implements ChronoLocalDate, Temporal, TemporalAdjuster, Serializable { - - /** - * Serialization version. - */ - private static final long serialVersionUID = 6282433883239719096L; - - /** - * Casts the {@code Temporal} to {@code ChronoLocalDate} ensuring it bas the specified chronology. - * - * @param chrono the chronology to check for, not null - * @param temporal a date-time to cast, not null - * @return the date-time checked and cast to {@code ChronoLocalDate}, not null - * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate - * or the chronology is not equal this Chronology - */ - static D ensureValid(Chronology chrono, Temporal temporal) { - @SuppressWarnings("unchecked") - D other = (D) temporal; - if (chrono.equals(other.getChronology()) == false) { - throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + other.getChronology().getId()); - } - return other; - } - - //----------------------------------------------------------------------- - /** - * Creates an instance. - */ - ChronoDateImpl() { - } - - @Override - @SuppressWarnings("unchecked") - public D with(TemporalAdjuster adjuster) { - return (D) ChronoLocalDate.super.with(adjuster); - } - - @Override - @SuppressWarnings("unchecked") - public D with(TemporalField field, long value) { - return (D) ChronoLocalDate.super.with(field, value); - } - - //----------------------------------------------------------------------- - @Override - @SuppressWarnings("unchecked") - public D plus(TemporalAmount amount) { - return (D) ChronoLocalDate.super.plus(amount); - } - - //----------------------------------------------------------------------- - @Override - @SuppressWarnings("unchecked") - public D plus(long amountToAdd, TemporalUnit unit) { - if (unit instanceof ChronoUnit) { - ChronoUnit f = (ChronoUnit) unit; - switch (f) { - case DAYS: return plusDays(amountToAdd); - case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7)); - case MONTHS: return plusMonths(amountToAdd); - case YEARS: return plusYears(amountToAdd); - case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); - case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); - case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); - case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); - } - throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); - } - return (D) ChronoLocalDate.super.plus(amountToAdd, unit); - } - - @Override - @SuppressWarnings("unchecked") - public D minus(TemporalAmount amount) { - return (D) ChronoLocalDate.super.minus(amount); - } - - @Override - @SuppressWarnings("unchecked") - public D minus(long amountToSubtract, TemporalUnit unit) { - return (D) ChronoLocalDate.super.minus(amountToSubtract, unit); - } - - //----------------------------------------------------------------------- - /** - * Returns a copy of this date with the specified period in years added. - *

- * This adds the specified period in years to the date. - * In some cases, adding years can cause the resulting date to become invalid. - * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure - * that the result is valid. Typically this will select the last valid day of the month. - *

- * This instance is immutable and unaffected by this method call. - * - * @param yearsToAdd the years to add, may be negative - * @return a date based on this one with the years added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - abstract D plusYears(long yearsToAdd); - - /** - * Returns a copy of this date with the specified period in months added. - *

- * This adds the specified period in months to the date. - * In some cases, adding months can cause the resulting date to become invalid. - * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure - * that the result is valid. Typically this will select the last valid day of the month. - *

- * This instance is immutable and unaffected by this method call. - * - * @param monthsToAdd the months to add, may be negative - * @return a date based on this one with the months added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - abstract D plusMonths(long monthsToAdd); - - /** - * Returns a copy of this date with the specified period in weeks added. - *

- * This adds the specified period in weeks to the date. - * In some cases, adding weeks can cause the resulting date to become invalid. - * If this occurs, then other fields will be adjusted to ensure that the result is valid. - *

- * The default implementation uses {@link #plusDays(long)} using a 7 day week. - *

- * This instance is immutable and unaffected by this method call. - * - * @param weeksToAdd the weeks to add, may be negative - * @return a date based on this one with the weeks added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - D plusWeeks(long weeksToAdd) { - return plusDays(Math.multiplyExact(weeksToAdd, 7)); - } - - /** - * Returns a copy of this date with the specified number of days added. - *

- * This adds the specified period in days to the date. - *

- * This instance is immutable and unaffected by this method call. - * - * @param daysToAdd the days to add, may be negative - * @return a date based on this one with the days added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - abstract D plusDays(long daysToAdd); - - //----------------------------------------------------------------------- - /** - * Returns a copy of this date with the specified period in years subtracted. - *

- * This subtracts the specified period in years to the date. - * In some cases, subtracting years can cause the resulting date to become invalid. - * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure - * that the result is valid. Typically this will select the last valid day of the month. - *

- * The default implementation uses {@link #plusYears(long)}. - *

- * This instance is immutable and unaffected by this method call. - * - * @param yearsToSubtract the years to subtract, may be negative - * @return a date based on this one with the years subtracted, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - @SuppressWarnings("unchecked") - D minusYears(long yearsToSubtract) { - return (yearsToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl)plusYears(Long.MAX_VALUE)).plusYears(1) : plusYears(-yearsToSubtract)); - } - - /** - * Returns a copy of this date with the specified period in months subtracted. - *

- * This subtracts the specified period in months to the date. - * In some cases, subtracting months can cause the resulting date to become invalid. - * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure - * that the result is valid. Typically this will select the last valid day of the month. - *

- * The default implementation uses {@link #plusMonths(long)}. - *

- * This instance is immutable and unaffected by this method call. - * - * @param monthsToSubtract the months to subtract, may be negative - * @return a date based on this one with the months subtracted, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - @SuppressWarnings("unchecked") - D minusMonths(long monthsToSubtract) { - return (monthsToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl)plusMonths(Long.MAX_VALUE)).plusMonths(1) : plusMonths(-monthsToSubtract)); - } - - /** - * Returns a copy of this date with the specified period in weeks subtracted. - *

- * This subtracts the specified period in weeks to the date. - * In some cases, subtracting weeks can cause the resulting date to become invalid. - * If this occurs, then other fields will be adjusted to ensure that the result is valid. - *

- * The default implementation uses {@link #plusWeeks(long)}. - *

- * This instance is immutable and unaffected by this method call. - * - * @param weeksToSubtract the weeks to subtract, may be negative - * @return a date based on this one with the weeks subtracted, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - @SuppressWarnings("unchecked") - D minusWeeks(long weeksToSubtract) { - return (weeksToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl)plusWeeks(Long.MAX_VALUE)).plusWeeks(1) : plusWeeks(-weeksToSubtract)); - } - - /** - * Returns a copy of this date with the specified number of days subtracted. - *

- * This subtracts the specified period in days to the date. - *

- * The default implementation uses {@link #plusDays(long)}. - *

- * This instance is immutable and unaffected by this method call. - * - * @param daysToSubtract the days to subtract, may be negative - * @return a date based on this one with the days subtracted, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - @SuppressWarnings("unchecked") - D minusDays(long daysToSubtract) { - return (daysToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl)plusDays(Long.MAX_VALUE)).plusDays(1) : plusDays(-daysToSubtract)); - } - - //----------------------------------------------------------------------- - /** - * {@inheritDoc} - * @throws DateTimeException {@inheritDoc} - * @throws ArithmeticException {@inheritDoc} - */ - @Override - public long until(Temporal endDateTime, TemporalUnit unit) { - Objects.requireNonNull(endDateTime, "endDateTime"); - Objects.requireNonNull(unit, "unit"); - if (endDateTime instanceof ChronoLocalDate == false) { - throw new DateTimeException("Unable to calculate amount as objects are of two different types"); - } - ChronoLocalDate end = (ChronoLocalDate) endDateTime; - if (getChronology().equals(end.getChronology()) == false) { - throw new DateTimeException("Unable to calculate amount as objects have different chronologies"); - } - if (unit instanceof ChronoUnit) { - switch ((ChronoUnit) unit) { - case DAYS: return daysUntil(end); - case WEEKS: return daysUntil(end) / 7; - case MONTHS: return monthsUntil(end); - case YEARS: return monthsUntil(end) / 12; - case DECADES: return monthsUntil(end) / 120; - case CENTURIES: return monthsUntil(end) / 1200; - case MILLENNIA: return monthsUntil(end) / 12000; - case ERAS: return end.getLong(ERA) - getLong(ERA); - } - throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); - } - return unit.between(this, endDateTime); - } - - private long daysUntil(ChronoLocalDate end) { - return end.toEpochDay() - toEpochDay(); // no overflow - } - - private long monthsUntil(ChronoLocalDate end) { - ValueRange range = getChronology().range(MONTH_OF_YEAR); - if (range.getMaximum() != 12) { - throw new IllegalStateException("ChronoDateImpl only supports Chronologies with 12 months per year"); - } - long packed1 = getLong(PROLEPTIC_MONTH) * 32L + get(DAY_OF_MONTH); // no overflow - long packed2 = end.getLong(PROLEPTIC_MONTH) * 32L + end.get(DAY_OF_MONTH); // no overflow - return (packed2 - packed1) / 32; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ChronoLocalDate) { - return compareTo((ChronoLocalDate) obj) == 0; - } - return false; - } - - @Override - public int hashCode() { - long epDay = toEpochDay(); - return getChronology().hashCode() ^ ((int) (epDay ^ (epDay >>> 32))); - } - - @Override - public String toString() { - // getLong() reduces chances of exceptions in toString() - long yoe = getLong(YEAR_OF_ERA); - long moy = getLong(MONTH_OF_YEAR); - long dom = getLong(DAY_OF_MONTH); - StringBuilder buf = new StringBuilder(30); - buf.append(getChronology().toString()) - .append(" ") - .append(getEra()) - .append(" ") - .append(yoe) - .append(moy < 10 ? "-0" : "-").append(moy) - .append(dom < 10 ? "-0" : "-").append(dom); - return buf.toString(); - } - -} diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java --- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java Fri Aug 30 11:43:57 2013 +0100 @@ -428,7 +428,7 @@ */ @Override default ChronoLocalDate with(TemporalAdjuster adjuster) { - return ChronoDateImpl.ensureValid(getChronology(), Temporal.super.with(adjuster)); + return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.with(adjuster)); } /** @@ -442,7 +442,7 @@ if (field instanceof ChronoField) { throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } - return ChronoDateImpl.ensureValid(getChronology(), field.adjustInto(this, newValue)); + return ChronoLocalDateImpl.ensureValid(getChronology(), field.adjustInto(this, newValue)); } /** @@ -452,7 +452,7 @@ */ @Override default ChronoLocalDate plus(TemporalAmount amount) { - return ChronoDateImpl.ensureValid(getChronology(), Temporal.super.plus(amount)); + return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.plus(amount)); } /** @@ -465,7 +465,7 @@ if (unit instanceof ChronoUnit) { throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } - return ChronoDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd)); + return ChronoLocalDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd)); } /** @@ -475,7 +475,7 @@ */ @Override default ChronoLocalDate minus(TemporalAmount amount) { - return ChronoDateImpl.ensureValid(getChronology(), Temporal.super.minus(amount)); + return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amount)); } /** @@ -486,7 +486,7 @@ */ @Override default ChronoLocalDate minus(long amountToSubtract, TemporalUnit unit) { - return ChronoDateImpl.ensureValid(getChronology(), Temporal.super.minus(amountToSubtract, unit)); + return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amountToSubtract, unit)); } //----------------------------------------------------------------------- diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/ChronoLocalDateImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDateImpl.java Fri Aug 30 11:43:57 2013 +0100 @@ -0,0 +1,455 @@ +/* + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of JSR-310 nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package java.time.chrono; + +import static java.time.temporal.ChronoField.DAY_OF_MONTH; +import static java.time.temporal.ChronoField.ERA; +import static java.time.temporal.ChronoField.MONTH_OF_YEAR; +import static java.time.temporal.ChronoField.PROLEPTIC_MONTH; +import static java.time.temporal.ChronoField.YEAR_OF_ERA; + +import java.io.Serializable; +import java.time.DateTimeException; +import java.time.temporal.ChronoUnit; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAdjuster; +import java.time.temporal.TemporalAmount; +import java.time.temporal.TemporalField; +import java.time.temporal.TemporalUnit; +import java.time.temporal.UnsupportedTemporalTypeException; +import java.time.temporal.ValueRange; +import java.util.Objects; + +/** + * A date expressed in terms of a standard year-month-day calendar system. + *

+ * This class is used by applications seeking to handle dates in non-ISO calendar systems. + * For example, the Japanese, Minguo, Thai Buddhist and others. + *

+ * {@code ChronoLocalDate} is built on the generic concepts of year, month and day. + * The calendar system, represented by a {@link java.time.chrono.Chronology}, expresses the relationship between + * the fields and this class allows the resulting date to be manipulated. + *

+ * Note that not all calendar systems are suitable for use with this class. + * For example, the Mayan calendar uses a system that bears no relation to years, months and days. + *

+ * The API design encourages the use of {@code LocalDate} for the majority of the application. + * This includes code to read and write from a persistent data store, such as a database, + * and to send dates and times across a network. The {@code ChronoLocalDate} instance is then used + * at the user interface level to deal with localized input/output. + * + *

Example:

+ *
+ *        System.out.printf("Example()%n");
+ *        // Enumerate the list of available calendars and print today for each
+ *        Set<Chronology> chronos = Chronology.getAvailableChronologies();
+ *        for (Chronology chrono : chronos) {
+ *            ChronoLocalDate date = chrono.dateNow();
+ *            System.out.printf("   %20s: %s%n", chrono.getID(), date.toString());
+ *        }
+ *
+ *        // Print the Hijrah date and calendar
+ *        ChronoLocalDate date = Chronology.of("Hijrah").dateNow();
+ *        int day = date.get(ChronoField.DAY_OF_MONTH);
+ *        int dow = date.get(ChronoField.DAY_OF_WEEK);
+ *        int month = date.get(ChronoField.MONTH_OF_YEAR);
+ *        int year = date.get(ChronoField.YEAR);
+ *        System.out.printf("  Today is %s %s %d-%s-%d%n", date.getChronology().getID(),
+ *                dow, day, month, year);
+
+ *        // Print today's date and the last day of the year
+ *        ChronoLocalDate now1 = Chronology.of("Hijrah").dateNow();
+ *        ChronoLocalDate first = now1.with(ChronoField.DAY_OF_MONTH, 1)
+ *                .with(ChronoField.MONTH_OF_YEAR, 1);
+ *        ChronoLocalDate last = first.plus(1, ChronoUnit.YEARS)
+ *                .minus(1, ChronoUnit.DAYS);
+ *        System.out.printf("  Today is %s: start: %s; end: %s%n", last.getChronology().getID(),
+ *                first, last);
+ * 
+ * + *

Adding Calendars

+ *

The set of calendars is extensible by defining a subclass of {@link ChronoLocalDate} + * to represent a date instance and an implementation of {@code Chronology} + * to be the factory for the ChronoLocalDate subclass. + *

+ *

To permit the discovery of the additional calendar types the implementation of + * {@code Chronology} must be registered as a Service implementing the {@code Chronology} interface + * in the {@code META-INF/Services} file as per the specification of {@link java.util.ServiceLoader}. + * The subclass must function according to the {@code Chronology} class description and must provide its + * {@link java.time.chrono.Chronology#getId() chronlogy ID} and {@link Chronology#getCalendarType() calendar type}.

+ * + * @implSpec + * This abstract class must be implemented with care to ensure other classes operate correctly. + * All implementations that can be instantiated must be final, immutable and thread-safe. + * Subclasses should be Serializable wherever possible. + * + * @param the ChronoLocalDate of this date-time + * @since 1.8 + */ +abstract class ChronoLocalDateImpl + implements ChronoLocalDate, Temporal, TemporalAdjuster, Serializable { + + /** + * Serialization version. + */ + private static final long serialVersionUID = 6282433883239719096L; + + /** + * Casts the {@code Temporal} to {@code ChronoLocalDate} ensuring it bas the specified chronology. + * + * @param chrono the chronology to check for, not null + * @param temporal a date-time to cast, not null + * @return the date-time checked and cast to {@code ChronoLocalDate}, not null + * @throws ClassCastException if the date-time cannot be cast to ChronoLocalDate + * or the chronology is not equal this Chronology + */ + static D ensureValid(Chronology chrono, Temporal temporal) { + @SuppressWarnings("unchecked") + D other = (D) temporal; + if (chrono.equals(other.getChronology()) == false) { + throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + other.getChronology().getId()); + } + return other; + } + + //----------------------------------------------------------------------- + /** + * Creates an instance. + */ + ChronoLocalDateImpl() { + } + + @Override + @SuppressWarnings("unchecked") + public D with(TemporalAdjuster adjuster) { + return (D) ChronoLocalDate.super.with(adjuster); + } + + @Override + @SuppressWarnings("unchecked") + public D with(TemporalField field, long value) { + return (D) ChronoLocalDate.super.with(field, value); + } + + //----------------------------------------------------------------------- + @Override + @SuppressWarnings("unchecked") + public D plus(TemporalAmount amount) { + return (D) ChronoLocalDate.super.plus(amount); + } + + //----------------------------------------------------------------------- + @Override + @SuppressWarnings("unchecked") + public D plus(long amountToAdd, TemporalUnit unit) { + if (unit instanceof ChronoUnit) { + ChronoUnit f = (ChronoUnit) unit; + switch (f) { + case DAYS: return plusDays(amountToAdd); + case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7)); + case MONTHS: return plusMonths(amountToAdd); + case YEARS: return plusYears(amountToAdd); + case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); + case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); + case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); + case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); + } + throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); + } + return (D) ChronoLocalDate.super.plus(amountToAdd, unit); + } + + @Override + @SuppressWarnings("unchecked") + public D minus(TemporalAmount amount) { + return (D) ChronoLocalDate.super.minus(amount); + } + + @Override + @SuppressWarnings("unchecked") + public D minus(long amountToSubtract, TemporalUnit unit) { + return (D) ChronoLocalDate.super.minus(amountToSubtract, unit); + } + + //----------------------------------------------------------------------- + /** + * Returns a copy of this date with the specified period in years added. + *

+ * This adds the specified period in years to the date. + * In some cases, adding years can cause the resulting date to become invalid. + * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure + * that the result is valid. Typically this will select the last valid day of the month. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param yearsToAdd the years to add, may be negative + * @return a date based on this one with the years added, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + abstract D plusYears(long yearsToAdd); + + /** + * Returns a copy of this date with the specified period in months added. + *

+ * This adds the specified period in months to the date. + * In some cases, adding months can cause the resulting date to become invalid. + * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure + * that the result is valid. Typically this will select the last valid day of the month. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param monthsToAdd the months to add, may be negative + * @return a date based on this one with the months added, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + abstract D plusMonths(long monthsToAdd); + + /** + * Returns a copy of this date with the specified period in weeks added. + *

+ * This adds the specified period in weeks to the date. + * In some cases, adding weeks can cause the resulting date to become invalid. + * If this occurs, then other fields will be adjusted to ensure that the result is valid. + *

+ * The default implementation uses {@link #plusDays(long)} using a 7 day week. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param weeksToAdd the weeks to add, may be negative + * @return a date based on this one with the weeks added, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + D plusWeeks(long weeksToAdd) { + return plusDays(Math.multiplyExact(weeksToAdd, 7)); + } + + /** + * Returns a copy of this date with the specified number of days added. + *

+ * This adds the specified period in days to the date. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param daysToAdd the days to add, may be negative + * @return a date based on this one with the days added, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + abstract D plusDays(long daysToAdd); + + //----------------------------------------------------------------------- + /** + * Returns a copy of this date with the specified period in years subtracted. + *

+ * This subtracts the specified period in years to the date. + * In some cases, subtracting years can cause the resulting date to become invalid. + * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure + * that the result is valid. Typically this will select the last valid day of the month. + *

+ * The default implementation uses {@link #plusYears(long)}. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param yearsToSubtract the years to subtract, may be negative + * @return a date based on this one with the years subtracted, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + @SuppressWarnings("unchecked") + D minusYears(long yearsToSubtract) { + return (yearsToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl)plusYears(Long.MAX_VALUE)).plusYears(1) : plusYears(-yearsToSubtract)); + } + + /** + * Returns a copy of this date with the specified period in months subtracted. + *

+ * This subtracts the specified period in months to the date. + * In some cases, subtracting months can cause the resulting date to become invalid. + * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure + * that the result is valid. Typically this will select the last valid day of the month. + *

+ * The default implementation uses {@link #plusMonths(long)}. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param monthsToSubtract the months to subtract, may be negative + * @return a date based on this one with the months subtracted, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + @SuppressWarnings("unchecked") + D minusMonths(long monthsToSubtract) { + return (monthsToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl)plusMonths(Long.MAX_VALUE)).plusMonths(1) : plusMonths(-monthsToSubtract)); + } + + /** + * Returns a copy of this date with the specified period in weeks subtracted. + *

+ * This subtracts the specified period in weeks to the date. + * In some cases, subtracting weeks can cause the resulting date to become invalid. + * If this occurs, then other fields will be adjusted to ensure that the result is valid. + *

+ * The default implementation uses {@link #plusWeeks(long)}. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param weeksToSubtract the weeks to subtract, may be negative + * @return a date based on this one with the weeks subtracted, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + @SuppressWarnings("unchecked") + D minusWeeks(long weeksToSubtract) { + return (weeksToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl)plusWeeks(Long.MAX_VALUE)).plusWeeks(1) : plusWeeks(-weeksToSubtract)); + } + + /** + * Returns a copy of this date with the specified number of days subtracted. + *

+ * This subtracts the specified period in days to the date. + *

+ * The default implementation uses {@link #plusDays(long)}. + *

+ * This instance is immutable and unaffected by this method call. + * + * @param daysToSubtract the days to subtract, may be negative + * @return a date based on this one with the days subtracted, not null + * @throws DateTimeException if the result exceeds the supported date range + */ + @SuppressWarnings("unchecked") + D minusDays(long daysToSubtract) { + return (daysToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl)plusDays(Long.MAX_VALUE)).plusDays(1) : plusDays(-daysToSubtract)); + } + + //----------------------------------------------------------------------- + /** + * {@inheritDoc} + * @throws DateTimeException {@inheritDoc} + * @throws ArithmeticException {@inheritDoc} + */ + @Override + public long until(Temporal endDateTime, TemporalUnit unit) { + Objects.requireNonNull(endDateTime, "endDateTime"); + Objects.requireNonNull(unit, "unit"); + if (endDateTime instanceof ChronoLocalDate == false) { + throw new DateTimeException("Unable to calculate amount as objects are of two different types"); + } + ChronoLocalDate end = (ChronoLocalDate) endDateTime; + if (getChronology().equals(end.getChronology()) == false) { + throw new DateTimeException("Unable to calculate amount as objects have different chronologies"); + } + if (unit instanceof ChronoUnit) { + switch ((ChronoUnit) unit) { + case DAYS: return daysUntil(end); + case WEEKS: return daysUntil(end) / 7; + case MONTHS: return monthsUntil(end); + case YEARS: return monthsUntil(end) / 12; + case DECADES: return monthsUntil(end) / 120; + case CENTURIES: return monthsUntil(end) / 1200; + case MILLENNIA: return monthsUntil(end) / 12000; + case ERAS: return end.getLong(ERA) - getLong(ERA); + } + throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); + } + return unit.between(this, endDateTime); + } + + private long daysUntil(ChronoLocalDate end) { + return end.toEpochDay() - toEpochDay(); // no overflow + } + + private long monthsUntil(ChronoLocalDate end) { + ValueRange range = getChronology().range(MONTH_OF_YEAR); + if (range.getMaximum() != 12) { + throw new IllegalStateException("ChronoLocalDateImpl only supports Chronologies with 12 months per year"); + } + long packed1 = getLong(PROLEPTIC_MONTH) * 32L + get(DAY_OF_MONTH); // no overflow + long packed2 = end.getLong(PROLEPTIC_MONTH) * 32L + end.get(DAY_OF_MONTH); // no overflow + return (packed2 - packed1) / 32; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof ChronoLocalDate) { + return compareTo((ChronoLocalDate) obj) == 0; + } + return false; + } + + @Override + public int hashCode() { + long epDay = toEpochDay(); + return getChronology().hashCode() ^ ((int) (epDay ^ (epDay >>> 32))); + } + + @Override + public String toString() { + // getLong() reduces chances of exceptions in toString() + long yoe = getLong(YEAR_OF_ERA); + long moy = getLong(MONTH_OF_YEAR); + long dom = getLong(DAY_OF_MONTH); + StringBuilder buf = new StringBuilder(30); + buf.append(getChronology().toString()) + .append(" ") + .append(getEra()) + .append(" ") + .append(yoe) + .append(moy < 10 ? "-0" : "-").append(moy) + .append(dom < 10 ? "-0" : "-").append(dom); + return buf.toString(); + } + +} diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/ChronoLocalDateTimeImpl.java --- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDateTimeImpl.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDateTimeImpl.java Fri Aug 30 11:43:57 2013 +0100 @@ -220,7 +220,7 @@ return this; } // Validate that the new Temporal is a ChronoLocalDate (and not something else) - D cd = ChronoDateImpl.ensureValid(date.getChronology(), newDate); + D cd = ChronoLocalDateImpl.ensureValid(date.getChronology(), newDate); return new ChronoLocalDateTimeImpl<>(cd, newTime); } diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/HijrahDate.java --- a/jdk/src/share/classes/java/time/chrono/HijrahDate.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/HijrahDate.java Fri Aug 30 11:43:57 2013 +0100 @@ -109,7 +109,7 @@ * @since 1.8 */ public final class HijrahDate - extends ChronoDateImpl + extends ChronoLocalDateImpl implements ChronoLocalDate, Serializable { /** diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/JapaneseDate.java --- a/jdk/src/share/classes/java/time/chrono/JapaneseDate.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/JapaneseDate.java Fri Aug 30 11:43:57 2013 +0100 @@ -61,10 +61,8 @@ import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; import static java.time.temporal.ChronoField.DAY_OF_MONTH; -import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; -import static java.time.temporal.ChronoField.YEAR_OF_ERA; import java.io.DataInput; import java.io.DataOutput; @@ -76,7 +74,6 @@ import java.time.LocalDate; import java.time.LocalTime; import java.time.Period; -import java.time.Year; import java.time.ZoneId; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; @@ -119,7 +116,7 @@ * @since 1.8 */ public final class JapaneseDate - extends ChronoDateImpl + extends ChronoLocalDateImpl implements ChronoLocalDate, Serializable { /** diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/MinguoDate.java --- a/jdk/src/share/classes/java/time/chrono/MinguoDate.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/MinguoDate.java Fri Aug 30 11:43:57 2013 +0100 @@ -96,7 +96,7 @@ * @since 1.8 */ public final class MinguoDate - extends ChronoDateImpl + extends ChronoLocalDateImpl implements ChronoLocalDate, Serializable { /** diff -r 1336a85b3d52 -r dde564773845 jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java --- a/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java Thu Aug 29 20:38:46 2013 +0100 +++ b/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java Fri Aug 30 11:43:57 2013 +0100 @@ -96,7 +96,7 @@ * @since 1.8 */ public final class ThaiBuddhistDate - extends ChronoDateImpl + extends ChronoLocalDateImpl implements ChronoLocalDate, Serializable { /**