1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package java.time.chrono;
  58 
  59 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  60 import static java.time.temporal.ChronoField.ERA;
  61 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  62 import static java.time.temporal.ChronoField.YEAR_OF_ERA;
  63 
  64 import java.io.Serializable;
  65 import java.time.DateTimeException;
  66 import java.time.LocalDate;
  67 import java.time.LocalTime;
  68 import java.time.chrono.Chronology;
  69 import java.time.chrono.ChronoLocalDate;
  70 import java.time.chrono.ChronoLocalDateTime;
  71 import java.time.temporal.ChronoUnit;
  72 import java.time.temporal.Temporal;
  73 import java.time.temporal.TemporalAdjuster;
  74 import java.time.temporal.TemporalUnit;
  75 
  76 /**
  77  * A date expressed in terms of a standard year-month-day calendar system.
  78  * <p>
  79  * This class is used by applications seeking to handle dates in non-ISO calendar systems.
  80  * For example, the Japanese, Minguo, Thai Buddhist and others.
  81  * <p>
  82  * {@code ChronoLocalDate} is built on the generic concepts of year, month and day.
  83  * The calendar system, represented by a {@link java.time.chrono.Chronology}, expresses the relationship between
  84  * the fields and this class allows the resulting date to be manipulated.
  85  * <p>
  86  * Note that not all calendar systems are suitable for use with this class.
  87  * For example, the Mayan calendar uses a system that bears no relation to years, months and days.
  88  * <p>
  89  * The API design encourages the use of {@code LocalDate} for the majority of the application.
  90  * This includes code to read and write from a persistent data store, such as a database,
  91  * and to send dates and times across a network. The {@code ChronoLocalDate} instance is then used
  92  * at the user interface level to deal with localized input/output.
  93  *
  94  * <P>Example: </p>
  95  * <pre>
  96  *        System.out.printf("Example()%n");
  97  *        // Enumerate the list of available calendars and print today for each
  98  *        Set&lt;Chronology&gt; chronos = Chronology.getAvailableChronologies();
  99  *        for (Chronology chrono : chronos) {
 100  *            ChronoLocalDate<?> date = chrono.dateNow();
 101  *            System.out.printf("   %20s: %s%n", chrono.getID(), date.toString());
 102  *        }
 103  *
 104  *        // Print the Hijrah date and calendar
 105  *        ChronoLocalDate<?> date = Chronology.of("Hijrah").dateNow();
 106  *        int day = date.get(ChronoField.DAY_OF_MONTH);
 107  *        int dow = date.get(ChronoField.DAY_OF_WEEK);
 108  *        int month = date.get(ChronoField.MONTH_OF_YEAR);
 109  *        int year = date.get(ChronoField.YEAR);
 110  *        System.out.printf("  Today is %s %s %d-%s-%d%n", date.getChronology().getID(),
 111  *                dow, day, month, year);
 112 
 113  *        // Print today's date and the last day of the year
 114  *        ChronoLocalDate<?> now1 = Chronology.of("Hijrah").dateNow();
 115  *        ChronoLocalDate<?> first = now1.with(ChronoField.DAY_OF_MONTH, 1)
 116  *                .with(ChronoField.MONTH_OF_YEAR, 1);
 117  *        ChronoLocalDate<?> last = first.plus(1, ChronoUnit.YEARS)
 118  *                .minus(1, ChronoUnit.DAYS);
 119  *        System.out.printf("  Today is %s: start: %s; end: %s%n", last.getChronology().getID(),
 120  *                first, last);
 121  * </pre>
 122  *
 123  * <h3>Adding Calendars</h3>
 124  * <p> The set of calendars is extensible by defining a subclass of {@link ChronoLocalDate}
 125  * to represent a date instance and an implementation of {@code Chronology}
 126  * to be the factory for the ChronoLocalDate subclass.
 127  * </p>
 128  * <p> To permit the discovery of the additional calendar types the implementation of
 129  * {@code Chronology} must be registered as a Service implementing the {@code Chronology} interface
 130  * in the {@code META-INF/Services} file as per the specification of {@link java.util.ServiceLoader}.
 131  * The subclass must function according to the {@code Chronology} class description and must provide its
 132  * {@link java.time.chrono.Chronology#getId() chronlogy ID} and {@link Chronology#getCalendarType() calendar type}. </p>
 133  *
 134  * <h3>Specification for implementors</h3>
 135  * This abstract class must be implemented with care to ensure other classes operate correctly.
 136  * All implementations that can be instantiated must be final, immutable and thread-safe.
 137  * Subclasses should be Serializable wherever possible.
 138  *
 139  * @param <D> the ChronoLocalDate of this date-time
 140  * @since 1.8
 141  */
 142 abstract class ChronoDateImpl<D extends ChronoLocalDate<D>>
 143         implements ChronoLocalDate<D>, Temporal, TemporalAdjuster, Serializable {
 144 
 145     /**
 146      * Serialization version.
 147      */
 148     private static final long serialVersionUID = 6282433883239719096L;
 149 
 150     /**
 151      * Creates an instance.
 152      */
 153     ChronoDateImpl() {
 154     }
 155 
 156     //-----------------------------------------------------------------------
 157     @Override
 158     public D plus(long amountToAdd, TemporalUnit unit) {
 159         if (unit instanceof ChronoUnit) {
 160             ChronoUnit f = (ChronoUnit) unit;
 161             switch (f) {
 162                 case DAYS: return plusDays(amountToAdd);
 163                 case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));
 164                 case MONTHS: return plusMonths(amountToAdd);
 165                 case YEARS: return plusYears(amountToAdd);
 166                 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
 167                 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
 168                 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
 169                 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
 170             }
 171             throw new DateTimeException("Unsupported unit: " + unit.getName());
 172         }
 173         return ChronoLocalDate.super.plus(amountToAdd, unit);
 174     }
 175 
 176     //-----------------------------------------------------------------------
 177     /**
 178      * Returns a copy of this date with the specified period in years added.
 179      * <p>
 180      * This adds the specified period in years to the date.
 181      * In some cases, adding years can cause the resulting date to become invalid.
 182      * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
 183      * that the result is valid. Typically this will select the last valid day of the month.
 184      * <p>
 185      * This instance is immutable and unaffected by this method call.
 186      *
 187      * @param yearsToAdd  the years to add, may be negative
 188      * @return a date based on this one with the years added, not null
 189      * @throws DateTimeException if the result exceeds the supported date range
 190      */
 191     abstract D plusYears(long yearsToAdd);
 192 
 193     /**
 194      * Returns a copy of this date with the specified period in months added.
 195      * <p>
 196      * This adds the specified period in months to the date.
 197      * In some cases, adding months can cause the resulting date to become invalid.
 198      * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
 199      * that the result is valid. Typically this will select the last valid day of the month.
 200      * <p>
 201      * This instance is immutable and unaffected by this method call.
 202      *
 203      * @param monthsToAdd  the months to add, may be negative
 204      * @return a date based on this one with the months added, not null
 205      * @throws DateTimeException if the result exceeds the supported date range
 206      */
 207     abstract D plusMonths(long monthsToAdd);
 208 
 209     /**
 210      * Returns a copy of this date with the specified period in weeks added.
 211      * <p>
 212      * This adds the specified period in weeks to the date.
 213      * In some cases, adding weeks can cause the resulting date to become invalid.
 214      * If this occurs, then other fields will be adjusted to ensure that the result is valid.
 215      * <p>
 216      * The default implementation uses {@link #plusDays(long)} using a 7 day week.
 217      * <p>
 218      * This instance is immutable and unaffected by this method call.
 219      *
 220      * @param weeksToAdd  the weeks to add, may be negative
 221      * @return a date based on this one with the weeks added, not null
 222      * @throws DateTimeException if the result exceeds the supported date range
 223      */
 224     D plusWeeks(long weeksToAdd) {
 225         return plusDays(Math.multiplyExact(weeksToAdd, 7));
 226     }
 227 
 228     /**
 229      * Returns a copy of this date with the specified number of days added.
 230      * <p>
 231      * This adds the specified period in days to the date.
 232      * <p>
 233      * This instance is immutable and unaffected by this method call.
 234      *
 235      * @param daysToAdd  the days to add, may be negative
 236      * @return a date based on this one with the days added, not null
 237      * @throws DateTimeException if the result exceeds the supported date range
 238      */
 239     abstract D plusDays(long daysToAdd);
 240 
 241     //-----------------------------------------------------------------------
 242     /**
 243      * Returns a copy of this date with the specified period in years subtracted.
 244      * <p>
 245      * This subtracts the specified period in years to the date.
 246      * In some cases, subtracting years can cause the resulting date to become invalid.
 247      * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
 248      * that the result is valid. Typically this will select the last valid day of the month.
 249      * <p>
 250      * The default implementation uses {@link #plusYears(long)}.
 251      * <p>
 252      * This instance is immutable and unaffected by this method call.
 253      *
 254      * @param yearsToSubtract  the years to subtract, may be negative
 255      * @return a date based on this one with the years subtracted, not null
 256      * @throws DateTimeException if the result exceeds the supported date range
 257      */
 258     D minusYears(long yearsToSubtract) {
 259         return (yearsToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl<D>)plusYears(Long.MAX_VALUE)).plusYears(1) : plusYears(-yearsToSubtract));
 260     }
 261 
 262     /**
 263      * Returns a copy of this date with the specified period in months subtracted.
 264      * <p>
 265      * This subtracts the specified period in months to the date.
 266      * In some cases, subtracting months can cause the resulting date to become invalid.
 267      * If this occurs, then other fields, typically the day-of-month, will be adjusted to ensure
 268      * that the result is valid. Typically this will select the last valid day of the month.
 269      * <p>
 270      * The default implementation uses {@link #plusMonths(long)}.
 271      * <p>
 272      * This instance is immutable and unaffected by this method call.
 273      *
 274      * @param monthsToSubtract  the months to subtract, may be negative
 275      * @return a date based on this one with the months subtracted, not null
 276      * @throws DateTimeException if the result exceeds the supported date range
 277      */
 278     D minusMonths(long monthsToSubtract) {
 279         return (monthsToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl<D>)plusMonths(Long.MAX_VALUE)).plusMonths(1) : plusMonths(-monthsToSubtract));
 280     }
 281 
 282     /**
 283      * Returns a copy of this date with the specified period in weeks subtracted.
 284      * <p>
 285      * This subtracts the specified period in weeks to the date.
 286      * In some cases, subtracting weeks can cause the resulting date to become invalid.
 287      * If this occurs, then other fields will be adjusted to ensure that the result is valid.
 288      * <p>
 289      * The default implementation uses {@link #plusWeeks(long)}.
 290      * <p>
 291      * This instance is immutable and unaffected by this method call.
 292      *
 293      * @param weeksToSubtract  the weeks to subtract, may be negative
 294      * @return a date based on this one with the weeks subtracted, not null
 295      * @throws DateTimeException if the result exceeds the supported date range
 296      */
 297     D minusWeeks(long weeksToSubtract) {
 298         return (weeksToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl<D>)plusWeeks(Long.MAX_VALUE)).plusWeeks(1) : plusWeeks(-weeksToSubtract));
 299     }
 300 
 301     /**
 302      * Returns a copy of this date with the specified number of days subtracted.
 303      * <p>
 304      * This subtracts the specified period in days to the date.
 305      * <p>
 306      * The default implementation uses {@link #plusDays(long)}.
 307      * <p>
 308      * This instance is immutable and unaffected by this method call.
 309      *
 310      * @param daysToSubtract  the days to subtract, may be negative
 311      * @return a date based on this one with the days subtracted, not null
 312      * @throws DateTimeException if the result exceeds the supported date range
 313      */
 314     D minusDays(long daysToSubtract) {
 315         return (daysToSubtract == Long.MIN_VALUE ? ((ChronoDateImpl<D>)plusDays(Long.MAX_VALUE)).plusDays(1) : plusDays(-daysToSubtract));
 316     }
 317 
 318     //-----------------------------------------------------------------------
 319     /**
 320      * {@inheritDoc}
 321      * @throws DateTimeException {@inheritDoc}
 322      * @throws ArithmeticException {@inheritDoc}
 323      */
 324     @Override
 325     public long periodUntil(Temporal endDateTime, TemporalUnit unit) {
 326         if (endDateTime instanceof ChronoLocalDate == false) {
 327             throw new DateTimeException("Unable to calculate period between objects of two different types");
 328         }
 329         ChronoLocalDate<?> end = (ChronoLocalDate<?>) endDateTime;
 330         if (getChronology().equals(end.getChronology()) == false) {
 331             throw new DateTimeException("Unable to calculate period between two different chronologies");
 332         }
 333         if (unit instanceof ChronoUnit) {
 334             return LocalDate.from(this).periodUntil(end, unit);  // TODO: this is wrong
 335         }
 336         return unit.between(this, endDateTime);
 337     }
 338 
 339     @Override
 340     public boolean equals(Object obj) {
 341         if (this == obj) {
 342             return true;
 343         }
 344         if (obj instanceof ChronoLocalDate) {
 345             return compareTo((ChronoLocalDate<?>) obj) == 0;
 346         }
 347         return false;
 348     }
 349 
 350     @Override
 351     public int hashCode() {
 352         long epDay = toEpochDay();
 353         return getChronology().hashCode() ^ ((int) (epDay ^ (epDay >>> 32)));
 354     }
 355 
 356     @Override
 357     public String toString() {
 358         // getLong() reduces chances of exceptions in toString()
 359         long yoe = getLong(YEAR_OF_ERA);
 360         long moy = getLong(MONTH_OF_YEAR);
 361         long dom = getLong(DAY_OF_MONTH);
 362         StringBuilder buf = new StringBuilder(30);
 363         buf.append(getChronology().toString())
 364                 .append(" ")
 365                 .append(getEra())
 366                 .append(" ")
 367                 .append(yoe)
 368                 .append(moy < 10 ? "-0" : "-").append(moy)
 369                 .append(dom < 10 ? "-0" : "-").append(dom);
 370         return buf.toString();
 371     }
 372 
 373 }