UNPKG

12 kBJavaScriptView Raw
1/*
2 * @copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper
3 * @copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
4 * @license BSD-3-Clause (see LICENSE in the root directory of this source tree)
5 */
6
7import {requireNonNull, requireInstance} from '../assert';
8
9import {ChronoField} from '../temporal/ChronoField';
10import {ChronoUnit} from '../temporal/ChronoUnit';
11import {DateTimeFormatter} from '../format/DateTimeFormatter';
12import {TemporalQueries} from '../temporal/TemporalQueries';
13import {DefaultInterfaceTemporal} from '../temporal/DefaultInterfaceTemporal';
14
15import {LocalDate} from '../LocalDate';
16
17/**
18 * A date without time-of-day or time-zone in an arbitrary chronology, intended
19 * for advanced globalization use cases.
20 *
21 * **Most applications should declare method signatures, fields and variables
22 * as {@link LocalDate}, not this interface.**
23 *
24 * A {@link ChronoLocalDate} is the abstract representation of a date where the
25 * {@link Chronology}, or calendar system, is pluggable.
26 * The date is defined in terms of fields expressed by {@link TemporalField},
27 * where most common implementations are defined in {@link ChronoField}.
28 * The chronology defines how the calendar system operates and the meaning of
29 * the standard fields.
30 *
31 * #### When to use this interface
32 *
33 * The design of the API encourages the use of {@link LocalDate} rather than this
34 * interface, even in the case where the application needs to deal with multiple
35 * calendar systems. The rationale for this is explored in the following documentation.
36 *
37 * The primary use case where this interface should be used is where the generic
38 * type parameter `C` is fully defined as a specific chronology.
39 * In that case, the assumptions of that chronology are known at development
40 * time and specified in the code.
41 *
42 * When the chronology is defined in the generic type parameter as ? or otherwise
43 * unknown at development time, the rest of the discussion below applies.
44 *
45 * To emphasize the point, declaring a method signature, field or variable as this
46 * interface type can initially seem like the sensible way to globalize an application,
47 * however it is usually the wrong approach.
48 * As such, it should be considered an application-wide architectural decision to choose
49 * to use this interface as opposed to {@link LocalDate}.
50 *
51 * #### Architectural issues to consider
52 *
53 * These are some of the points that must be considered before using this interface
54 * throughout an application.
55 *
56 * 1) Applications using this interface, as opposed to using just {@link LocalDate},
57 * face a significantly higher probability of bugs. This is because the calendar system
58 * in use is not known at development time. A key cause of bugs is where the developer
59 * applies assumptions from their day-to-day knowledge of the ISO calendar system
60 * to code that is intended to deal with any arbitrary calendar system.
61 * The section below outlines how those assumptions can cause problems
62 * The primary mechanism for reducing this increased risk of bugs is a strong code review process.
63 * This should also be considered a extra cost in maintenance for the lifetime of the code.
64 *
65 * 2) This interface does not enforce immutability of implementations.
66 * While the implementation notes indicate that all implementations must be immutable
67 * there is nothing in the code or type system to enforce this. Any method declared
68 * to accept a {@link ChronoLocalDate} could therefore be passed a poorly or
69 * maliciously written mutable implementation.
70 *
71 * 3) Applications using this interface must consider the impact of eras.
72 * {@link LocalDate} shields users from the concept of eras, by ensuring that `getYear()`
73 * returns the proleptic year. That decision ensures that developers can think of
74 * {@link LocalDate} instances as consisting of three fields - year, month-of-year and day-of-month.
75 * By contrast, users of this interface must think of dates as consisting of four fields -
76 * era, year-of-era, month-of-year and day-of-month. The extra era field is frequently
77 * forgotten, yet it is of vital importance to dates in an arbitrary calendar system.
78 * For example, in the Japanese calendar system, the era represents the reign of an Emperor.
79 * Whenever one reign ends and another starts, the year-of-era is reset to one.
80 *
81 * 4) The only agreed international standard for passing a date between two systems
82 * is the ISO-8601 standard which requires the ISO calendar system. Using this interface
83 * throughout the application will inevitably lead to the requirement to pass the date
84 * across a network or component boundary, requiring an application specific protocol or format.
85 *
86 * 5) Long term persistence, such as a database, will almost always only accept dates in the
87 * ISO-8601 calendar system (or the related Julian-Gregorian). Passing around dates in other
88 * calendar systems increases the complications of interacting with persistence.
89 *
90 * 6) Most of the time, passing a {@link ChronoLocalDate} throughout an application
91 * is unnecessary, as discussed in the last section below.
92 *
93 * #### False assumptions causing bugs in multi-calendar system code
94 *
95 * As indicated above, there are many issues to consider when try to use and manipulate a
96 * date in an arbitrary calendar system. These are some of the key issues.
97 *
98 * Code that queries the day-of-month and assumes that the value will never be more than
99 * 31 is invalid. Some calendar systems have more than 31 days in some months.
100 *
101 * Code that adds 12 months to a date and assumes that a year has been added is invalid.
102 * Some calendar systems have a different number of months, such as 13 in the Coptic or Ethiopic.
103 *
104 * Code that adds one month to a date and assumes that the month-of-year value will increase
105 * by one or wrap to the next year is invalid. Some calendar systems have a variable number
106 * of months in a year, such as the Hebrew.
107 *
108 * Code that adds one month, then adds a second one month and assumes that the day-of-month
109 * will remain close to its original value is invalid. Some calendar systems have a large difference
110 * between the length of the longest month and the length of the shortest month.
111 * For example, the Coptic or Ethiopic have 12 months of 30 days and 1 month of 5 days.
112 *
113 * Code that adds seven days and assumes that a week has been added is invalid.
114 * Some calendar systems have weeks of other than seven days, such as the French Revolutionary.
115 *
116 * Code that assumes that because the year of `date1` is greater than the year of `date2`
117 * then `date1` is after `date2` is invalid. This is invalid for all calendar systems
118 * when referring to the year-of-era, and especially untrue of the Japanese calendar system
119 * where the year-of-era restarts with the reign of every new Emperor.
120 *
121 * Code that treats month-of-year one and day-of-month one as the start of the year is invalid.
122 * Not all calendar systems start the year when the month value is one.
123 *
124 * In general, manipulating a date, and even querying a date, is wide open to bugs when the
125 * calendar system is unknown at development time. This is why it is essential that code using
126 * this interface is subjected to additional code reviews. It is also why an architectural
127 * decision to avoid this interface type is usually the correct one.
128 *
129 * #### Using LocalDate instead
130 *
131 * The primary alternative to using this interface throughout your application is as follows.
132 *
133 * * Declare all method signatures referring to dates in terms of {@link LocalDate}.
134 * * Either store the chronology (calendar system) in the user profile or lookup the chronology
135 * from the user locale.
136 * * Convert the ISO {@link LocalDate} to and from the user's preferred calendar system during
137 * printing and parsing.
138 *
139 * This approach treats the problem of globalized calendar systems as a localization issue
140 * and confines it to the UI layer. This approach is in keeping with other localization
141 * issues in the java platform.
142 *
143 * As discussed above, performing calculations on a date where the rules of the calendar system
144 * are pluggable requires skill and is not recommended.
145 * Fortunately, the need to perform calculations on a date in an arbitrary calendar system
146 * is extremely rare. For example, it is highly unlikely that the business rules of a library
147 * book rental scheme will allow rentals to be for one month, where meaning of the month
148 * is dependent on the user's preferred calendar system.
149 *
150 * A key use case for calculations on a date in an arbitrary calendar system is producing
151 * a month-by-month calendar for display and user interaction. Again, this is a UI issue,
152 * and use of this interface solely within a few methods of the UI layer may be justified.
153 *
154 * In any other part of the system, where a date must be manipulated in a calendar system
155 * other than ISO, the use case will generally specify the calendar system to use.
156 * For example, an application may need to calculate the next Islamic or Hebrew holiday
157 * which may require manipulating the date.
158 * This kind of use case can be handled as follows:
159 *
160 * * start from the ISO {@link LocalDate} being passed to the method
161 * * convert the date to the alternate calendar system, which for this use case is known
162 * rather than arbitrary
163 * * perform the calculation
164 * * convert back to {@link LocalDate}
165 *
166 * Developers writing low-level frameworks or libraries should also avoid this interface.
167 * Instead, one of the two general purpose access interfaces should be used.
168 * Use {@link TemporalAccessor} if read-only access is required, or use {@link Temporal}
169 * if read-write access is required.
170 *
171 * ### Specification for implementors
172 *
173 * This interface must be implemented with care to ensure other classes operate correctly.
174 * All implementations that can be instantiated must be final, immutable and thread-safe.
175 * Subclasses should be Serializable wherever possible.
176 *
177 * Additional calendar systems may be added to the system.
178 * See {@link Chronology} for more details.
179 *
180 * In JDK 8, this is an interface with default methods.
181 * Since there are no default methods in JDK 7, an abstract class is used.
182 */
183export class ChronoLocalDate extends DefaultInterfaceTemporal {
184
185 isSupported(fieldOrUnit) {
186 if (fieldOrUnit instanceof ChronoField) {
187 return fieldOrUnit.isDateBased();
188 } else if (fieldOrUnit instanceof ChronoUnit) {
189 return fieldOrUnit.isDateBased();
190 }
191 return fieldOrUnit != null && fieldOrUnit.isSupportedBy(this);
192 }
193
194 query(query) {
195 if (query === TemporalQueries.chronology()) {
196 return this.chronology();
197 } else if (query === TemporalQueries.precision()) {
198 return ChronoUnit.DAYS;
199 } else if (query === TemporalQueries.localDate()) {
200 return LocalDate.ofEpochDay(this.toEpochDay());
201 } else if (query === TemporalQueries.localTime() || query === TemporalQueries.zone() ||
202 query === TemporalQueries.zoneId() || query === TemporalQueries.offset()) {
203 return null;
204 }
205 return super.query(query);
206 }
207
208 adjustInto(temporal) {
209 return temporal.with(ChronoField.EPOCH_DAY, this.toEpochDay());
210 }
211 /**
212 * Formats this date using the specified formatter.
213 *
214 * This date will be passed to the formatter to produce a string.
215 *
216 * The default implementation must behave as follows:
217 * <pre>
218 * return formatter.format(this);
219 * </pre>
220 *
221 * @param {DateTimeFormatter} formatter the formatter to use, not null
222 * @return {String} the formatted date string, not null
223 * @throws DateTimeException if an error occurs during printing
224 */
225 format(formatter) {
226 requireNonNull(formatter, 'formatter');
227 requireInstance(formatter, DateTimeFormatter, 'formatter');
228 return formatter.format(this);
229 }
230}