blob: 8b4fe9267da10cfad2c21a3a7a2106bd4e3ac72d [file] [log] [blame]
Stephen Colebournedf4d2352013-01-22 20:59:21 -08001/*
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 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file:
31 *
32 * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
33 *
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions are met:
38 *
39 * * Redistributions of source code must retain the above copyright notice,
40 * this list of conditions and the following disclaimer.
41 *
42 * * Redistributions in binary form must reproduce the above copyright notice,
43 * this list of conditions and the following disclaimer in the documentation
44 * and/or other materials provided with the distribution.
45 *
46 * * Neither the name of JSR-310 nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61 */
62package java.time;
63
64import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
65import static java.time.temporal.ChronoUnit.MONTHS;
66
Stephen Colebourne73c043f2013-02-12 09:25:43 -080067import java.time.chrono.Chronology;
68import java.time.chrono.IsoChronology;
Stephen Colebournedf4d2352013-01-22 20:59:21 -080069import java.time.format.DateTimeFormatterBuilder;
70import java.time.format.TextStyle;
Stephen Colebournedf4d2352013-01-22 20:59:21 -080071import java.time.temporal.ChronoField;
Stephen Colebournedf4d2352013-01-22 20:59:21 -080072import java.time.temporal.Queries;
73import java.time.temporal.Temporal;
74import java.time.temporal.TemporalAccessor;
75import java.time.temporal.TemporalAdjuster;
76import java.time.temporal.TemporalField;
77import java.time.temporal.TemporalQuery;
78import java.time.temporal.ValueRange;
79import java.util.Locale;
80
81/**
82 * A month-of-year, such as 'July'.
83 * <p>
84 * {@code Month} is an enum representing the 12 months of the year -
85 * January, February, March, April, May, June, July, August, September, October,
86 * November and December.
87 * <p>
88 * In addition to the textual enum name, each month-of-year has an {@code int} value.
89 * The {@code int} value follows normal usage and the ISO-8601 standard,
90 * from 1 (January) to 12 (December). It is recommended that applications use the enum
91 * rather than the {@code int} value to ensure code clarity.
92 * <p>
93 * <b>Do not use {@code ordinal()} to obtain the numeric representation of {@code Month}.
94 * Use {@code getValue()} instead.</b>
95 * <p>
96 * This enum represents a common concept that is found in many calendar systems.
97 * As such, this enum may be used by any calendar system that has the month-of-year
98 * concept defined exactly equivalent to the ISO-8601 calendar system.
99 *
100 * <h3>Specification for implementors</h3>
101 * This is an immutable and thread-safe enum.
102 *
103 * @since 1.8
104 */
105public enum Month implements TemporalAccessor, TemporalAdjuster {
106
107 /**
108 * The singleton instance for the month of January with 31 days.
109 * This has the numeric value of {@code 1}.
110 */
111 JANUARY,
112 /**
113 * The singleton instance for the month of February with 28 days, or 29 in a leap year.
114 * This has the numeric value of {@code 2}.
115 */
116 FEBRUARY,
117 /**
118 * The singleton instance for the month of March with 31 days.
119 * This has the numeric value of {@code 3}.
120 */
121 MARCH,
122 /**
123 * The singleton instance for the month of April with 30 days.
124 * This has the numeric value of {@code 4}.
125 */
126 APRIL,
127 /**
128 * The singleton instance for the month of May with 31 days.
129 * This has the numeric value of {@code 5}.
130 */
131 MAY,
132 /**
133 * The singleton instance for the month of June with 30 days.
134 * This has the numeric value of {@code 6}.
135 */
136 JUNE,
137 /**
138 * The singleton instance for the month of July with 31 days.
139 * This has the numeric value of {@code 7}.
140 */
141 JULY,
142 /**
143 * The singleton instance for the month of August with 31 days.
144 * This has the numeric value of {@code 8}.
145 */
146 AUGUST,
147 /**
148 * The singleton instance for the month of September with 30 days.
149 * This has the numeric value of {@code 9}.
150 */
151 SEPTEMBER,
152 /**
153 * The singleton instance for the month of October with 31 days.
154 * This has the numeric value of {@code 10}.
155 */
156 OCTOBER,
157 /**
158 * The singleton instance for the month of November with 30 days.
159 * This has the numeric value of {@code 11}.
160 */
161 NOVEMBER,
162 /**
163 * The singleton instance for the month of December with 31 days.
164 * This has the numeric value of {@code 12}.
165 */
166 DECEMBER;
167 /**
168 * Private cache of all the constants.
169 */
170 private static final Month[] ENUMS = Month.values();
171
172 //-----------------------------------------------------------------------
173 /**
174 * Obtains an instance of {@code Month} from an {@code int} value.
175 * <p>
176 * {@code Month} is an enum representing the 12 months of the year.
177 * This factory allows the enum to be obtained from the {@code int} value.
178 * The {@code int} value follows the ISO-8601 standard, from 1 (January) to 12 (December).
179 *
180 * @param month the month-of-year to represent, from 1 (January) to 12 (December)
181 * @return the month-of-year, not null
182 * @throws DateTimeException if the month-of-year is invalid
183 */
184 public static Month of(int month) {
185 if (month < 1 || month > 12) {
186 throw new DateTimeException("Invalid value for MonthOfYear: " + month);
187 }
188 return ENUMS[month - 1];
189 }
190
191 //-----------------------------------------------------------------------
192 /**
193 * Obtains an instance of {@code Month} from a temporal object.
194 * <p>
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800195 * This obtains a month based on the specified temporal.
196 * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
197 * which this factory converts to an instance of {@code Month}.
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800198 * <p>
199 * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} field.
200 * The extraction is only permitted if the temporal object has an ISO
201 * chronology, or can be converted to a {@code LocalDate}.
202 * <p>
203 * This method matches the signature of the functional interface {@link TemporalQuery}
204 * allowing it to be used in queries via method reference, {@code Month::from}.
205 *
206 * @param temporal the temporal object to convert, not null
207 * @return the month-of-year, not null
208 * @throws DateTimeException if unable to convert to a {@code Month}
209 */
210 public static Month from(TemporalAccessor temporal) {
211 if (temporal instanceof Month) {
212 return (Month) temporal;
213 }
214 try {
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800215 if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800216 temporal = LocalDate.from(temporal);
217 }
218 return of(temporal.get(MONTH_OF_YEAR));
219 } catch (DateTimeException ex) {
220 throw new DateTimeException("Unable to obtain Month from TemporalAccessor: " + temporal.getClass(), ex);
221 }
222 }
223
224 //-----------------------------------------------------------------------
225 /**
226 * Gets the month-of-year {@code int} value.
227 * <p>
228 * The values are numbered following the ISO-8601 standard,
229 * from 1 (January) to 12 (December).
230 *
231 * @return the month-of-year, from 1 (January) to 12 (December)
232 */
233 public int getValue() {
234 return ordinal() + 1;
235 }
236
237 //-----------------------------------------------------------------------
238 /**
239 * Gets the textual representation, such as 'Jan' or 'December'.
240 * <p>
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800241 * This returns the textual name used to identify the month-of-year,
242 * suitable for presentation to the user.
243 * The parameters control the style of the returned text and the locale.
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800244 * <p>
245 * If no textual mapping is found then the {@link #getValue() numeric value} is returned.
246 *
247 * @param style the length of the text required, not null
248 * @param locale the locale to use, not null
249 * @return the text value of the month-of-year, not null
250 */
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800251 public String getDisplayName(TextStyle style, Locale locale) {
252 return new DateTimeFormatterBuilder().appendText(MONTH_OF_YEAR, style).toFormatter(locale).format(this);
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800253 }
254
255 //-----------------------------------------------------------------------
256 /**
257 * Checks if the specified field is supported.
258 * <p>
259 * This checks if this month-of-year can be queried for the specified field.
260 * If false, then calling the {@link #range(TemporalField) range} and
261 * {@link #get(TemporalField) get} methods will throw an exception.
262 * <p>
263 * If the field is {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} then
264 * this method returns true.
265 * All other {@code ChronoField} instances will return false.
266 * <p>
267 * If the field is not a {@code ChronoField}, then the result of this method
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800268 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800269 * passing {@code this} as the argument.
270 * Whether the field is supported is determined by the field.
271 *
272 * @param field the field to check, null returns false
273 * @return true if the field is supported on this month-of-year, false if not
274 */
275 @Override
276 public boolean isSupported(TemporalField field) {
277 if (field instanceof ChronoField) {
278 return field == MONTH_OF_YEAR;
279 }
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800280 return field != null && field.isSupportedBy(this);
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800281 }
282
283 /**
284 * Gets the range of valid values for the specified field.
285 * <p>
286 * The range object expresses the minimum and maximum valid values for a field.
287 * This month is used to enhance the accuracy of the returned range.
288 * If it is not possible to return the range, because the field is not supported
289 * or for some other reason, an exception is thrown.
290 * <p>
291 * If the field is {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} then the
292 * range of the month-of-year, from 1 to 12, will be returned.
293 * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
294 * <p>
295 * If the field is not a {@code ChronoField}, then the result of this method
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800296 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800297 * passing {@code this} as the argument.
298 * Whether the range can be obtained is determined by the field.
299 *
300 * @param field the field to query the range for, not null
301 * @return the range of valid values for the field, not null
302 * @throws DateTimeException if the range for the field cannot be obtained
303 */
304 @Override
305 public ValueRange range(TemporalField field) {
306 if (field == MONTH_OF_YEAR) {
307 return field.range();
308 }
309 return TemporalAccessor.super.range(field);
310 }
311
312 /**
313 * Gets the value of the specified field from this month-of-year as an {@code int}.
314 * <p>
315 * This queries this month for the value for the specified field.
316 * The returned value will always be within the valid range of values for the field.
317 * If it is not possible to return the value, because the field is not supported
318 * or for some other reason, an exception is thrown.
319 * <p>
320 * If the field is {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} then the
321 * value of the month-of-year, from 1 to 12, will be returned.
322 * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
323 * <p>
324 * If the field is not a {@code ChronoField}, then the result of this method
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800325 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800326 * passing {@code this} as the argument. Whether the value can be obtained,
327 * and what the value represents, is determined by the field.
328 *
329 * @param field the field to get, not null
330 * @return the value for the field, within the valid range of values
331 * @throws DateTimeException if a value for the field cannot be obtained
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800332 * @throws ArithmeticException if numeric overflow occurs
333 */
334 @Override
335 public int get(TemporalField field) {
336 if (field == MONTH_OF_YEAR) {
337 return getValue();
338 }
339 return TemporalAccessor.super.get(field);
340 }
341
342 /**
343 * Gets the value of the specified field from this month-of-year as a {@code long}.
344 * <p>
345 * This queries this month for the value for the specified field.
346 * If it is not possible to return the value, because the field is not supported
347 * or for some other reason, an exception is thrown.
348 * <p>
349 * If the field is {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} then the
350 * value of the month-of-year, from 1 to 12, will be returned.
351 * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
352 * <p>
353 * If the field is not a {@code ChronoField}, then the result of this method
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800354 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800355 * passing {@code this} as the argument. Whether the value can be obtained,
356 * and what the value represents, is determined by the field.
357 *
358 * @param field the field to get, not null
359 * @return the value for the field
360 * @throws DateTimeException if a value for the field cannot be obtained
361 * @throws ArithmeticException if numeric overflow occurs
362 */
363 @Override
364 public long getLong(TemporalField field) {
365 if (field == MONTH_OF_YEAR) {
366 return getValue();
367 } else if (field instanceof ChronoField) {
368 throw new DateTimeException("Unsupported field: " + field.getName());
369 }
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800370 return field.getFrom(this);
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800371 }
372
373 //-----------------------------------------------------------------------
374 /**
375 * Returns the month-of-year that is the specified number of quarters after this one.
376 * <p>
377 * The calculation rolls around the end of the year from December to January.
378 * The specified period may be negative.
379 * <p>
380 * This instance is immutable and unaffected by this method call.
381 *
382 * @param months the months to add, positive or negative
383 * @return the resulting month, not null
384 */
385 public Month plus(long months) {
386 int amount = (int) (months % 12);
387 return ENUMS[(ordinal() + (amount + 12)) % 12];
388 }
389
390 /**
391 * Returns the month-of-year that is the specified number of months before this one.
392 * <p>
393 * The calculation rolls around the start of the year from January to December.
394 * The specified period may be negative.
395 * <p>
396 * This instance is immutable and unaffected by this method call.
397 *
398 * @param months the months to subtract, positive or negative
399 * @return the resulting month, not null
400 */
401 public Month minus(long months) {
402 return plus(-(months % 12));
403 }
404
405 //-----------------------------------------------------------------------
406 /**
407 * Gets the length of this month in days.
408 * <p>
409 * This takes a flag to determine whether to return the length for a leap year or not.
410 * <p>
411 * February has 28 days in a standard year and 29 days in a leap year.
412 * April, June, September and November have 30 days.
413 * All other months have 31 days.
414 *
415 * @param leapYear true if the length is required for a leap year
416 * @return the length of this month in days, from 28 to 31
417 */
418 public int length(boolean leapYear) {
419 switch (this) {
420 case FEBRUARY:
421 return (leapYear ? 29 : 28);
422 case APRIL:
423 case JUNE:
424 case SEPTEMBER:
425 case NOVEMBER:
426 return 30;
427 default:
428 return 31;
429 }
430 }
431
432 /**
433 * Gets the minimum length of this month in days.
434 * <p>
435 * February has a minimum length of 28 days.
436 * April, June, September and November have 30 days.
437 * All other months have 31 days.
438 *
439 * @return the minimum length of this month in days, from 28 to 31
440 */
441 public int minLength() {
442 switch (this) {
443 case FEBRUARY:
444 return 28;
445 case APRIL:
446 case JUNE:
447 case SEPTEMBER:
448 case NOVEMBER:
449 return 30;
450 default:
451 return 31;
452 }
453 }
454
455 /**
456 * Gets the maximum length of this month in days.
457 * <p>
458 * February has a maximum length of 29 days.
459 * April, June, September and November have 30 days.
460 * All other months have 31 days.
461 *
462 * @return the maximum length of this month in days, from 29 to 31
463 */
464 public int maxLength() {
465 switch (this) {
466 case FEBRUARY:
467 return 29;
468 case APRIL:
469 case JUNE:
470 case SEPTEMBER:
471 case NOVEMBER:
472 return 30;
473 default:
474 return 31;
475 }
476 }
477
478 //-----------------------------------------------------------------------
479 /**
480 * Gets the day-of-year corresponding to the first day of this month.
481 * <p>
482 * This returns the day-of-year that this month begins on, using the leap
483 * year flag to determine the length of February.
484 *
485 * @param leapYear true if the length is required for a leap year
486 * @return the day of year corresponding to the first day of this month, from 1 to 336
487 */
488 public int firstDayOfYear(boolean leapYear) {
489 int leap = leapYear ? 1 : 0;
490 switch (this) {
491 case JANUARY:
492 return 1;
493 case FEBRUARY:
494 return 32;
495 case MARCH:
496 return 60 + leap;
497 case APRIL:
498 return 91 + leap;
499 case MAY:
500 return 121 + leap;
501 case JUNE:
502 return 152 + leap;
503 case JULY:
504 return 182 + leap;
505 case AUGUST:
506 return 213 + leap;
507 case SEPTEMBER:
508 return 244 + leap;
509 case OCTOBER:
510 return 274 + leap;
511 case NOVEMBER:
512 return 305 + leap;
513 case DECEMBER:
514 default:
515 return 335 + leap;
516 }
517 }
518
519 /**
520 * Gets the month corresponding to the first month of this quarter.
521 * <p>
522 * The year can be divided into four quarters.
523 * This method returns the first month of the quarter for the base month.
524 * January, February and March return January.
525 * April, May and June return April.
526 * July, August and September return July.
527 * October, November and December return October.
528 *
529 * @return the first month of the quarter corresponding to this month, not null
530 */
531 public Month firstMonthOfQuarter() {
532 return ENUMS[(ordinal() / 3) * 3];
533 }
534
535 //-----------------------------------------------------------------------
536 /**
537 * Queries this month-of-year using the specified query.
538 * <p>
539 * This queries this month-of-year using the specified query strategy object.
540 * The {@code TemporalQuery} object defines the logic to be used to
541 * obtain the result. Read the documentation of the query to understand
542 * what the result of this method will be.
543 * <p>
544 * The result of this method is obtained by invoking the
545 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
546 * specified query passing {@code this} as the argument.
547 *
548 * @param <R> the type of the result
549 * @param query the query to invoke, not null
550 * @return the query result, null may be returned (defined by the query)
551 * @throws DateTimeException if unable to query (defined by the query)
552 * @throws ArithmeticException if numeric overflow occurs (defined by the query)
553 */
554 @SuppressWarnings("unchecked")
555 @Override
556 public <R> R query(TemporalQuery<R> query) {
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800557 if (query == Queries.chronology()) {
558 return (R) IsoChronology.INSTANCE;
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800559 } else if (query == Queries.precision()) {
560 return (R) MONTHS;
561 }
562 return TemporalAccessor.super.query(query);
563 }
564
565 /**
566 * Adjusts the specified temporal object to have this month-of-year.
567 * <p>
568 * This returns a temporal object of the same observable type as the input
569 * with the month-of-year changed to be the same as this.
570 * <p>
571 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
572 * passing {@link ChronoField#MONTH_OF_YEAR} as the field.
573 * If the specified temporal object does not use the ISO calendar system then
574 * a {@code DateTimeException} is thrown.
575 * <p>
576 * In most cases, it is clearer to reverse the calling pattern by using
577 * {@link Temporal#with(TemporalAdjuster)}:
578 * <pre>
579 * // these two lines are equivalent, but the second approach is recommended
580 * temporal = thisMonth.adjustInto(temporal);
581 * temporal = temporal.with(thisMonth);
582 * </pre>
583 * <p>
584 * For example, given a date in May, the following are output:
585 * <pre>
586 * dateInMay.with(JANUARY); // four months earlier
587 * dateInMay.with(APRIL); // one months earlier
588 * dateInMay.with(MAY); // same date
589 * dateInMay.with(JUNE); // one month later
590 * dateInMay.with(DECEMBER); // seven months later
591 * </pre>
592 * <p>
593 * This instance is immutable and unaffected by this method call.
594 *
595 * @param temporal the target object to be adjusted, not null
596 * @return the adjusted object, not null
597 * @throws DateTimeException if unable to make the adjustment
598 * @throws ArithmeticException if numeric overflow occurs
599 */
600 @Override
601 public Temporal adjustInto(Temporal temporal) {
Stephen Colebourne73c043f2013-02-12 09:25:43 -0800602 if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
Stephen Colebournedf4d2352013-01-22 20:59:21 -0800603 throw new DateTimeException("Adjustment only supported on ISO date-time");
604 }
605 return temporal.with(MONTH_OF_YEAR, getValue());
606 }
607
608}