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.calendar; |
|
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.temporal.Chrono; |
|
69 import java.time.temporal.ChronoLocalDate; |
|
70 import java.time.temporal.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.temporal.Chrono}, 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<Chrono> chronos = Chrono.getAvailableChronologies(); |
|
99 * for (Chrono 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 = Chrono.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.getChrono().getID(), |
|
111 * dow, day, month, year); |
|
112 |
|
113 * // Print today's date and the last day of the year |
|
114 * ChronoLocalDate<?> now1 = Chrono.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.getChrono().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 Chrono} |
|
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 Chrono} must be registered as a Service implementing the {@code Chrono} 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 Chrono} class description and must provide its |
|
132 * {@link java.time.temporal.Chrono#getId() chronlogy ID} and {@link Chrono#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 <C> the chronology of this date |
|
140 * @since 1.8 |
|
141 */ |
|
142 abstract class ChronoDateImpl<C extends Chrono<C>> |
|
143 implements ChronoLocalDate<C>, 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 ChronoLocalDate<C> 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 ChronoDateImpl<C> 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 ChronoDateImpl<C> 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 ChronoDateImpl<C> 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 ChronoDateImpl<C> 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 ChronoDateImpl<C> minusYears(long yearsToSubtract) { |
|
259 return (yearsToSubtract == Long.MIN_VALUE ? 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 ChronoDateImpl<C> minusMonths(long monthsToSubtract) { |
|
279 return (monthsToSubtract == Long.MIN_VALUE ? 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 ChronoDateImpl<C> minusWeeks(long weeksToSubtract) { |
|
298 return (weeksToSubtract == Long.MIN_VALUE ? 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 ChronoDateImpl<C> minusDays(long daysToSubtract) { |
|
315 return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); |
|
316 } |
|
317 |
|
318 @Override |
|
319 public final ChronoLocalDateTime<C> atTime(LocalTime localTime) { |
|
320 return Chrono.dateTime(this, localTime); |
|
321 } |
|
322 |
|
323 //----------------------------------------------------------------------- |
|
324 /** |
|
325 * {@inheritDoc} |
|
326 * @throws DateTimeException {@inheritDoc} |
|
327 * @throws ArithmeticException {@inheritDoc} |
|
328 */ |
|
329 @Override |
|
330 public long periodUntil(Temporal endDateTime, TemporalUnit unit) { |
|
331 if (endDateTime instanceof ChronoLocalDate == false) { |
|
332 throw new DateTimeException("Unable to calculate period between objects of two different types"); |
|
333 } |
|
334 ChronoLocalDate<?> end = (ChronoLocalDate<?>) endDateTime; |
|
335 if (getChrono().equals(end.getChrono()) == false) { |
|
336 throw new DateTimeException("Unable to calculate period between two different chronologies"); |
|
337 } |
|
338 if (unit instanceof ChronoUnit) { |
|
339 return LocalDate.from(this).periodUntil(end, unit); // TODO: this is wrong |
|
340 } |
|
341 return unit.between(this, endDateTime).getAmount(); |
|
342 } |
|
343 |
|
344 @Override |
|
345 public boolean equals(Object obj) { |
|
346 if (this == obj) { |
|
347 return true; |
|
348 } |
|
349 if (obj instanceof ChronoLocalDate) { |
|
350 return compareTo((ChronoLocalDate<?>) obj) == 0; |
|
351 } |
|
352 return false; |
|
353 } |
|
354 |
|
355 @Override |
|
356 public int hashCode() { |
|
357 long epDay = toEpochDay(); |
|
358 return getChrono().hashCode() ^ ((int) (epDay ^ (epDay >>> 32))); |
|
359 } |
|
360 |
|
361 @Override |
|
362 public String toString() { |
|
363 // getLong() reduces chances of exceptions in toString() |
|
364 long yoe = getLong(YEAR_OF_ERA); |
|
365 long moy = getLong(MONTH_OF_YEAR); |
|
366 long dom = getLong(DAY_OF_MONTH); |
|
367 StringBuilder buf = new StringBuilder(30); |
|
368 buf.append(getChrono().toString()) |
|
369 .append(" ") |
|
370 .append(getEra()) |
|
371 .append(" ") |
|
372 .append(yoe) |
|
373 .append(moy < 10 ? "-0" : "-").append(moy) |
|
374 .append(dom < 10 ? "-0" : "-").append(dom); |
|
375 return buf.toString(); |
|
376 } |
|
377 |
|
378 } |
|