001/*
002 * Copyright (c) 2007-2013, Stephen Colebourne & Michael Nascimento Santos
003 *
004 * All rights reserved.
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions are met:
008 *
009 *  * Redistributions of source code must retain the above copyright notice,
010 *    this list of conditions and the following disclaimer.
011 *
012 *  * Redistributions in binary form must reproduce the above copyright notice,
013 *    this list of conditions and the following disclaimer in the documentation
014 *    and/or other materials provided with the distribution.
015 *
016 *  * Neither the name of JSR-310 nor the names of its contributors
017 *    may be used to endorse or promote products derived from this software
018 *    without specific prior written permission.
019 *
020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
021 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
022 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
023 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
024 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
025 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
026 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
027 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
028 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
029 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
030 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
031 */
032package org.threeten.bp.temporal;
033
034import java.util.Comparator;
035
036import org.threeten.bp.DateTimeException;
037import org.threeten.bp.LocalDate;
038import org.threeten.bp.LocalTime;
039import org.threeten.bp.format.DateTimeFormatter;
040
041/**
042 * A date without time-of-day or time-zone in an arbitrary chronology, intended
043 * for advanced globalization use cases.
044 * <p>
045 * <b>Most applications should declare method signatures, fields and variables
046 * as {@link LocalDate}, not this interface.</b>
047 * <p>
048 * A {@code ChronoLocalDate} is the abstract representation of a date where the
049 * {@code Chrono chronology}, or calendar system, is pluggable.
050 * The date is defined in terms of fields expressed by {@link TemporalField},
051 * where most common implementations are defined in {@link ChronoField}.
052 * The chronology defines how the calendar system operates and the meaning of
053 * the standard fields.
054 *
055 * <h4>When to use this interface</h4>
056 * The design of the API encourages the use of {@code LocalDate} rather than this
057 * interface, even in the case where the application needs to deal with multiple
058 * calendar systems. The rationale for this is explored in the following documentation.
059 * <p>
060 * The primary use case where this interface should be used is where the generic
061 * type parameter {@code <C>} is fully defined as a specific chronology.
062 * In that case, the assumptions of that chronology are known at development
063 * time and specified in the code.
064 * <p>
065 * When the chronology is defined in the generic type parameter as ? or otherwise
066 * unknown at development time, the rest of the discussion below applies.
067 * <p>
068 * To emphasize the point, declaring a method signature, field or variable as this
069 * interface type can initially seem like the sensible way to globalize an application,
070 * however it is usually the wrong approach.
071 * As such, it should be considered an application-wide architectural decision to choose
072 * to use this interface as opposed to {@code LocalDate}.
073 *
074 * <h4>Architectural issues to consider</h4>
075 * These are some of the points that must be considered before using this interface
076 * throughout an application.
077 * <p>
078 * 1) Applications using this interface, as opposed to using just {@code LocalDate},
079 * face a significantly higher probability of bugs. This is because the calendar system
080 * in use is not known at development time. A key cause of bugs is where the developer
081 * applies assumptions from their day-to-day knowledge of the ISO calendar system
082 * to code that is intended to deal with any arbitrary calendar system.
083 * The section below outlines how those assumptions can cause problems
084 * The primary mechanism for reducing this increased risk of bugs is a strong code review process.
085 * This should also be considered a extra cost in maintenance for the lifetime of the code.
086 * <p>
087 * 2) This interface does not enforce immutability of implementations.
088 * While the implementation notes indicate that all implementations must be immutable
089 * there is nothing in the code or type system to enforce this. Any method declared
090 * to accept a {@code ChronoLocalDate} could therefore be passed a poorly or
091 * maliciously written mutable implementation.
092 * <p>
093 * 3) Applications using this interface  must consider the impact of eras.
094 * {@code LocalDate} shields users from the concept of eras, by ensuring that {@code getYear()}
095 * returns the proleptic year. That decision ensures that developers can think of
096 * {@code LocalDate} instances as consisting of three fields - year, month-of-year and day-of-month.
097 * By contrast, users of this interface must think of dates as consisting of four fields -
098 * era, year-of-era, month-of-year and day-of-month. The extra era field is frequently
099 * forgotten, yet it is of vital importance to dates in an arbitrary calendar system.
100 * For example, in the Japanese calendar system, the era represents the reign of an Emperor.
101 * Whenever one reign ends and another starts, the year-of-era is reset to one.
102 * <p>
103 * 4) The only agreed international standard for passing a date between two systems
104 * is the ISO-8601 standard which requires the ISO calendar system. Using this interface
105 * throughout the application will inevitably lead to the requirement to pass the date
106 * across a network or component boundary, requiring an application specific protocol or format.
107 * <p>
108 * 5) Long term persistence, such as a database, will almost always only accept dates in the
109 * ISO-8601 calendar system (or the related Julian-Gregorian). Passing around dates in other
110 * calendar systems increases the complications of interacting with persistence.
111 * <p>
112 * 6) Most of the time, passing a {@code ChronoLocalDate} throughout an application
113 * is unnecessary, as discussed in the last section below.
114 *
115 * <h4>False assumptions causing bugs in multi-calendar system code</h4>
116 * As indicated above, there are many issues to consider when try to use and manipulate a
117 * date in an arbitrary calendar system. These are some of the key issues.
118 * <p>
119 * Code that queries the day-of-month and assumes that the value will never be more than
120 * 31 is invalid. Some calendar systems have more than 31 days in some months.
121 * <p>
122 * Code that adds 12 months to a date and assumes that a year has been added is invalid.
123 * Some calendar systems have a different number of months, such as 13 in the Coptic or Ethiopic.
124 * <p>
125 * Code that adds one month to a date and assumes that the month-of-year value will increase
126 * by one or wrap to the next year is invalid. Some calendar systems have a variable number
127 * of months in a year, such as the Hebrew.
128 * <p>
129 * Code that adds one month, then adds a second one month and assumes that the day-of-month
130 * will remain close to its original value is invalid. Some calendar systems have a large difference
131 * between the length of the longest month and the length of the shortest month.
132 * For example, the Coptic or Ethiopic have 12 months of 30 days and 1 month of 5 days.
133 * <p>
134 * Code that adds seven days and assumes that a week has been added is invalid.
135 * Some calendar systems have weeks of other than seven days, such as the French Revolutionary.
136 * <p>
137 * Code that assumes that because the year of {@code date1} is greater than the year of {@code date2}
138 * then {@code date1} is after {@code date2} is invalid. This is invalid for all calendar systems
139 * when referring to the year-of-era, and especially untrue of the Japanese calendar system
140 * where the year-of-era restarts with the reign of every new Emperor.
141 * <p>
142 * Code that treats month-of-year one and day-of-month one as the start of the year is invalid.
143 * Not all calendar systems start the year when the month value is one.
144 * <p>
145 * In general, manipulating a date, and even querying a date, is wide open to bugs when the
146 * calendar system is unknown at development time. This is why it is essential that code using
147 * this interface is subjected to additional code reviews. It is also why an architectural
148 * decision to avoid this interface type is usually the correct one.
149 *
150 * <h4>Using LocalDate instead</h4>
151 * The primary alternative to using this interface throughout your application is as follows.
152 * <p><ul>
153 * <li>Declare all method signatures referring to dates in terms of {@code LocalDate}.
154 * <li>Either store the chronology (calendar system) in the user profile or lookup
155 *  the chronology from the user locale
156 * <li>Convert the ISO {@code LocalDate} to and from the user's preferred calendar system during
157 *  printing and parsing
158 * </ul><p>
159 * This approach treats the problem of globalized calendar systems as a localization issue
160 * and confines it to the UI layer. This approach is in keeping with other localization
161 * issues in the java platform.
162 * <p>
163 * As discussed above, performing calculations on a date where the rules of the calendar system
164 * are pluggable requires skill and is not recommended.
165 * Fortunately, the need to perform calculations on a date in an arbitrary calendar system
166 * is extremely rare. For example, it is highly unlikely that the business rules of a library
167 * book rental scheme will allow rentals to be for one month, where meaning of the month
168 * is dependent on the user's preferred calendar system.
169 * <p>
170 * A key use case for calculations on a date in an arbitrary calendar system is producing
171 * a month-by-month calendar for display and user interaction. Again, this is a UI issue,
172 * and use of this interface solely within a few methods of the UI layer may be justified.
173 * <p>
174 * In any other part of the system, where a date must be manipulated in a calendar system
175 * other than ISO, the use case will generally specify the calendar system to use.
176 * For example, an application may need to calculate the next Islamic or Hebrew holiday
177 * which may require manipulating the date.
178 * This kind of use case can be handled as follows:
179 * <p><ul>
180 * <li>start from the ISO {@code LocalDate} being passed to the method
181 * <li>convert the date to the alternate calendar system, which for this use case is known
182 *  rather than arbitrary
183 * <li>perform the calculation
184 * <li>convert back to {@code LocalDate}
185 * </ul><p>
186 * Developers writing low-level frameworks or libraries should also avoid this interface.
187 * Instead, one of the two general purpose access interfaces should be used.
188 * Use {@link TemporalAccessor} if read-only access is required, or use {@link Temporal}
189 * if read-write access is required.
190 *
191 * <h3>Specification for implementors</h3>
192 * This interface must be implemented with care to ensure other classes operate correctly.
193 * All implementations that can be instantiated must be final, immutable and thread-safe.
194 * Subclasses should be Serializable wherever possible.
195 * <p>
196 * Additional calendar systems may be added to the system.
197 * See {@link Chrono} for more details.
198 *
199 * @param <C> the chronology of this date
200 */
201public interface ChronoLocalDate<C extends Chrono<C>>
202        extends Temporal, TemporalAdjuster, Comparable<ChronoLocalDate<?>> {
203
204    /**
205     * Comparator for two {@code ChronoLocalDate}s ignoring the chronology.
206     * <p>
207     * This comparator differs from the comparison in {@link #compareTo} in that it
208     * only compares the underlying date and not the chronology.
209     * This allows dates in different calendar systems to be compared based
210     * on the time-line position.
211     * This is equivalent to using {@code Long.compare(date1.toEpochDay(),  date2.toEpochDay())}.
212     *
213     * @see #isAfter
214     * @see #isBefore
215     * @see #isEqual
216     */
217    public static final Comparator<ChronoLocalDate<?>> DATE_COMPARATOR =
218            new Comparator<ChronoLocalDate<?>>() {
219        @Override
220        public int compare(ChronoLocalDate<?> date1, ChronoLocalDate<?> date2) {
221            return Long.compare(date1.toEpochDay(), date2.toEpochDay());
222        }
223    };
224
225    /**
226     * Gets the chronology of this date.
227     * <p>
228     * The {@code Chrono} represents the calendar system in use.
229     * The era and other fields in {@link ChronoField} are defined by the chronology.
230     *
231     * @return the chronology, not null
232     */
233    C getChrono();
234
235    /**
236     * Gets the era, as defined by the chronology.
237     * <p>
238     * The era is, conceptually, the largest division of the time-line.
239     * Most calendar systems have a single epoch dividing the time-line into two eras.
240     * However, some have multiple eras, such as one for the reign of each leader.
241     * The exact meaning is determined by the {@code Chrono}.
242     * <p>
243     * All correctly implemented {@code Era} classes are singletons, thus it
244     * is valid code to write {@code date.getEra() == SomeChrono.ERA_NAME)}.
245     *
246     * @return the chronology specific era constant applicable at this date, not null
247     */
248    Era<C> getEra();
249
250    //-----------------------------------------------------------------------
251    /**
252     * Checks if the year is a leap year, as defined by the calendar system.
253     * <p>
254     * A leap-year is a year of a longer length than normal.
255     * The exact meaning is determined by the chronology with the constraint that
256     * a leap-year must imply a year-length longer than a non leap-year.
257     * <p>
258     * The default implementation uses {@link Chrono#isLeapYear(long)}.
259     *
260     * @return true if this date is in a leap year, false otherwise
261     */
262    boolean isLeapYear();
263
264    /**
265     * Returns the length of the month represented by this date, as defined by the calendar system.
266     * <p>
267     * This returns the length of the month in days.
268     *
269     * @return the length of the month in days
270     */
271    int lengthOfMonth();
272
273    /**
274     * Returns the length of the year represented by this date, as defined by the calendar system.
275     * <p>
276     * This returns the length of the year in days.
277     * <p>
278     * The default implementation uses {@link #isLeapYear()} and returns 365 or 366.
279     *
280     * @return the length of the year in days
281     */
282    int lengthOfYear();
283
284    //-------------------------------------------------------------------------
285    // override for covariant return type
286    @Override
287    ChronoLocalDate<C> with(TemporalAdjuster adjuster);
288
289    @Override
290    ChronoLocalDate<C> with(TemporalField field, long newValue);
291
292    @Override
293    ChronoLocalDate<C> plus(TemporalAdder adjuster);
294
295    @Override
296    ChronoLocalDate<C> plus(long amountToAdd, TemporalUnit unit);
297
298    @Override
299    ChronoLocalDate<C> minus(TemporalSubtractor adjuster);
300
301    @Override
302    ChronoLocalDate<C> minus(long amountToSubtract, TemporalUnit unit);
303
304    //-----------------------------------------------------------------------
305    /**
306     * Returns a date-time formed from this date at the specified time.
307     * <p>
308     * This merges the two objects - {@code this} and the specified time -
309     * to form an instance of {@code ChronoLocalDateTime}.
310     * <p>
311     * This instance is immutable and unaffected by this method call.
312     *
313     * @param localTime  the local time to use, not null
314     * @return the local date-time formed from this date and the specified time, not null
315     */
316    ChronoLocalDateTime<C> atTime(LocalTime localTime);
317
318    //-----------------------------------------------------------------------
319    /**
320     * Converts this date to the Epoch Day.
321     * <p>
322     * The {@link ChronoField#EPOCH_DAY Epoch Day count} is a simple
323     * incrementing count of days where day 0 is 1970-01-01 (ISO).
324     * This definition is the same for all chronologies, enabling conversion.
325     *
326     * @return the Epoch Day equivalent to this date
327     */
328    long toEpochDay();
329
330    //-----------------------------------------------------------------------
331    /**
332     * Compares this date to another date, including the chronology.
333     * <p>
334     * The comparison is based first on the underlying time-line date, then
335     * on the chronology.
336     * It is "consistent with equals", as defined by {@link Comparable}.
337     * <p>
338     * For example, the following is the comparator order:
339     * <ol>
340     * <li>{@code 2012-12-03 (ISO)}</li>
341     * <li>{@code 2012-12-04 (ISO)}</li>
342     * <li>{@code 2555-12-04 (ThaiBuddhist)}</li>
343     * <li>{@code 2012-12-05 (ISO)}</li>
344     * </ol>
345     * Values #2 and #3 represent the same date on the time-line.
346     * When two values represent the same date, the chronology ID is compared to distinguish them.
347     * This step is needed to make the ordering "consistent with equals".
348     * <p>
349     * If all the date objects being compared are in the same chronology, then the
350     * additional chronology stage is not required and only the local date is used.
351     * To compare the dates of two {@code DateTimeAccessor} instances, including dates
352     * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
353     *
354     * @param other  the other date to compare to, not null
355     * @return the comparator value, negative if less, positive if greater
356     */
357    @Override
358    int compareTo(ChronoLocalDate<?> other);
359
360    //-----------------------------------------------------------------------
361    /**
362     * Checks if this date is after the specified date ignoring the chronology.
363     * <p>
364     * This method differs from the comparison in {@link #compareTo} in that it
365     * only compares the underlying date and not the chronology.
366     * This allows dates in different calendar systems to be compared based
367     * on the time-line position.
368     * This is equivalent to using {@code date1.toEpochDay() &gt; date2.toEpochDay()}.
369     *
370     * @param other  the other date to compare to, not null
371     * @return true if this is after the specified date
372     */
373    boolean isAfter(ChronoLocalDate<?> other);
374
375    /**
376     * Checks if this date is before the specified date ignoring the chronology.
377     * <p>
378     * This method differs from the comparison in {@link #compareTo} in that it
379     * only compares the underlying date and not the chronology.
380     * This allows dates in different calendar systems to be compared based
381     * on the time-line position.
382     * This is equivalent to using {@code date1.toEpochDay() &lt; date2.toEpochDay()}.
383     *
384     * @param other  the other date to compare to, not null
385     * @return true if this is before the specified date
386     */
387    boolean isBefore(ChronoLocalDate<?> other);
388
389    /**
390     * Checks if this date is equal to the specified date ignoring the chronology.
391     * <p>
392     * This method differs from the comparison in {@link #compareTo} in that it
393     * only compares the underlying date and not the chronology.
394     * This allows dates in different calendar systems to be compared based
395     * on the time-line position.
396     * This is equivalent to using {@code date1.toEpochDay() == date2.toEpochDay()}.
397     *
398     * @param other  the other date to compare to, not null
399     * @return true if the underlying date is equal to the specified date
400     */
401    boolean isEqual(ChronoLocalDate<?> other);
402
403    //-----------------------------------------------------------------------
404    /**
405     * Checks if this date is equal to another date, including the chronology.
406     * <p>
407     * Compares this date with another ensuring that the date and chronology are the same.
408     * <p>
409     * To compare the dates of two {@code DateTimeAccessor} instances, including dates
410     * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
411     *
412     * @param obj  the object to check, null returns false
413     * @return true if this is equal to the other date
414     */
415    @Override
416    boolean equals(Object obj);
417
418    /**
419     * A hash code for this date.
420     *
421     * @return a suitable hash code
422     */
423    @Override
424    int hashCode();
425
426    //-----------------------------------------------------------------------
427    /**
428     * Outputs this date as a {@code String}.
429     * <p>
430     * The output will include the full local date and the chronology ID.
431     *
432     * @return the formatted date, not null
433     */
434    @Override
435    String toString();
436
437    /**
438     * Outputs this date-time as a {@code String} using the formatter.
439     *
440     * @param formatter  the formatter to use, not null
441     * @return the formatted date-time string, not null
442     * @throws DateTimeException if an error occurs during printing
443     */
444    String toString(DateTimeFormatter formatter);
445
446}