View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.time;
18  
19  import java.text.ParseException;
20  import java.text.ParsePosition;
21  import java.time.LocalDateTime;
22  import java.time.OffsetDateTime;
23  import java.time.ZoneId;
24  import java.time.ZonedDateTime;
25  import java.util.Calendar;
26  import java.util.Date;
27  import java.util.Iterator;
28  import java.util.Locale;
29  import java.util.NoSuchElementException;
30  import java.util.Objects;
31  import java.util.TimeZone;
32  import java.util.concurrent.TimeUnit;
33  
34  import org.apache.commons.lang3.LocaleUtils;
35  
36  /**
37   * A suite of utilities surrounding the use of the
38   * {@link java.util.Calendar} and {@link java.util.Date} object.
39   *
40   * <p>DateUtils contains a lot of common methods considering manipulations
41   * of Dates or Calendars. Some methods require some extra explanation.
42   * The truncate, ceiling and round methods could be considered the Math.floor(),
43   * Math.ceil() or Math.round versions for dates
44   * This way date-fields will be ignored in bottom-up order.
45   * As a complement to these methods we've introduced some fragment-methods.
46   * With these methods the Date-fields will be ignored in top-down order.
47   * Since a date without a year is not a valid date, you have to decide in what
48   * kind of date-field you want your result, for instance milliseconds or days.
49   * </p>
50   * <p>
51   * Several methods are provided for adding to {@link Date} objects, of the form
52   * {@code addXXX(Date date, int amount)}. It is important to note these methods
53   * use a {@link Calendar} internally (with default time zone and locale) and may
54   * be affected by changes to daylight saving time (DST).
55   * </p>
56   *
57   * @since 2.0
58   */
59  public class DateUtils {
60  
61      /**
62       * Date iterator.
63       */
64      static final class DateIterator implements Iterator<Calendar> {
65          private final Calendar endFinal;
66          private final Calendar spot;
67  
68          /**
69           * Constructs a DateIterator that ranges from one date to another.
70           *
71           * @param startFinal start date (inclusive)
72           * @param endFinal end date (inclusive)
73           */
74          DateIterator(final Calendar startFinal, final Calendar endFinal) {
75              this.endFinal = endFinal;
76              spot = startFinal;
77              spot.add(Calendar.DATE, -1);
78          }
79  
80          /**
81           * Has the iterator not reached the end date yet?
82           *
83           * @return {@code true} if the iterator has yet to reach the end date
84           */
85          @Override
86          public boolean hasNext() {
87              return spot.before(endFinal);
88          }
89  
90          /**
91           * Returns the next calendar in the iteration
92           *
93           * @return Object calendar for the next date
94           */
95          @Override
96          public Calendar next() {
97              if (spot.equals(endFinal)) {
98                  throw new NoSuchElementException();
99              }
100             spot.add(Calendar.DATE, 1);
101             return (Calendar) spot.clone();
102         }
103 
104         /**
105          * Always throws UnsupportedOperationException.
106          *
107          * @throws UnsupportedOperationException Always thrown.
108          * @see java.util.Iterator#remove()
109          */
110         @Override
111         public void remove() {
112             throw new UnsupportedOperationException();
113         }
114     }
115 
116     /**
117      * Calendar modification types.
118      */
119     private enum ModifyType {
120         /**
121          * Truncation.
122          */
123         TRUNCATE,
124 
125         /**
126          * Rounding.
127          */
128         ROUND,
129 
130         /**
131          * Ceiling.
132          */
133         CEILING
134     }
135 
136     /**
137      * Number of milliseconds in a standard second.
138      *
139      * @since 2.1
140      */
141     public static final long MILLIS_PER_SECOND = 1_000;
142 
143     /**
144      * Number of milliseconds in a standard minute.
145      *
146      * @since 2.1
147      */
148     public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
149 
150     /**
151      * Number of milliseconds in a standard hour.
152      *
153      * @since 2.1
154      */
155     public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
156 
157     /**
158      * Number of milliseconds in a standard day.
159      *
160      * @since 2.1
161      */
162     public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
163 
164     /**
165      * This is half a month, so this represents whether a date is in the top
166      * or bottom half of the month.
167      */
168     public static final int SEMI_MONTH = 1001;
169     private static final int[][] fields = {
170             {Calendar.MILLISECOND},
171             {Calendar.SECOND},
172             {Calendar.MINUTE},
173             {Calendar.HOUR_OF_DAY, Calendar.HOUR},
174             {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM
175                 /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
176             },
177             {Calendar.MONTH, SEMI_MONTH},
178             {Calendar.YEAR},
179             {Calendar.ERA}};
180     /**
181      * A week range, starting on Sunday.
182      */
183     public static final int RANGE_WEEK_SUNDAY = 1;
184 
185     /**
186      * A week range, starting on Monday.
187      */
188     public static final int RANGE_WEEK_MONDAY = 2;
189 
190     /**
191      * A week range, starting on the day focused.
192      */
193     public static final int RANGE_WEEK_RELATIVE = 3;
194 
195     /**
196      * A week range, centered around the day focused.
197      */
198     public static final int RANGE_WEEK_CENTER = 4;
199 
200     /**
201      * A month range, the week starting on Sunday.
202      */
203     public static final int RANGE_MONTH_SUNDAY = 5;
204 
205     /**
206      * A month range, the week starting on Monday.
207      */
208     public static final int RANGE_MONTH_MONDAY = 6;
209 
210     /**
211      * Adds to a date returning a new object.
212      * The original {@link Date} is unchanged.
213      *
214      * @param date  the date, not null
215      * @param calendarField  the calendar field to add to
216      * @param amount  the amount to add, may be negative
217      * @return the new {@link Date} with the amount added
218      * @throws NullPointerException if the date is null
219      */
220     private static Date add(final Date date, final int calendarField, final int amount) {
221         validateDateNotNull(date);
222         final Calendar c = Calendar.getInstance();
223         c.setTime(date);
224         c.add(calendarField, amount);
225         return c.getTime();
226     }
227 
228     /**
229      * Adds a number of days to a date returning a new object.
230      * The original {@link Date} is unchanged.
231      *
232      * @param date  the date, not null
233      * @param amount  the amount to add, may be negative
234      * @return the new {@link Date} with the amount added
235      * @throws NullPointerException if the date is null
236      */
237     public static Date addDays(final Date date, final int amount) {
238         return add(date, Calendar.DAY_OF_MONTH, amount);
239     }
240 
241     /**
242      * Adds a number of hours to a date returning a new object.
243      * The original {@link Date} is unchanged.
244      *
245      * @param date  the date, not null
246      * @param amount  the amount to add, may be negative
247      * @return the new {@link Date} with the amount added
248      * @throws NullPointerException if the date is null
249      */
250     public static Date addHours(final Date date, final int amount) {
251         return add(date, Calendar.HOUR_OF_DAY, amount);
252     }
253 
254     /**
255      * Adds a number of milliseconds to a date returning a new object.
256      * The original {@link Date} is unchanged.
257      *
258      * @param date  the date, not null
259      * @param amount  the amount to add, may be negative
260      * @return the new {@link Date} with the amount added
261      * @throws NullPointerException if the date is null
262      */
263     public static Date addMilliseconds(final Date date, final int amount) {
264         return add(date, Calendar.MILLISECOND, amount);
265     }
266 
267     /**
268      * Adds a number of minutes to a date returning a new object.
269      * The original {@link Date} is unchanged.
270      *
271      * @param date  the date, not null
272      * @param amount  the amount to add, may be negative
273      * @return the new {@link Date} with the amount added
274      * @throws NullPointerException if the date is null
275      */
276     public static Date addMinutes(final Date date, final int amount) {
277         return add(date, Calendar.MINUTE, amount);
278     }
279 
280     /**
281      * Adds a number of months to a date returning a new object.
282      * The original {@link Date} is unchanged.
283      *
284      * @param date  the date, not null
285      * @param amount  the amount to add, may be negative
286      * @return the new {@link Date} with the amount added
287      * @throws NullPointerException if the date is null
288      */
289     public static Date addMonths(final Date date, final int amount) {
290         return add(date, Calendar.MONTH, amount);
291     }
292 
293     /**
294      * Adds a number of seconds to a date returning a new object.
295      * The original {@link Date} is unchanged.
296      *
297      * @param date  the date, not null
298      * @param amount  the amount to add, may be negative
299      * @return the new {@link Date} with the amount added
300      * @throws NullPointerException if the date is null
301      */
302     public static Date addSeconds(final Date date, final int amount) {
303         return add(date, Calendar.SECOND, amount);
304     }
305 
306     /**
307      * Adds a number of weeks to a date returning a new object.
308      * The original {@link Date} is unchanged.
309      *
310      * @param date  the date, not null
311      * @param amount  the amount to add, may be negative
312      * @return the new {@link Date} with the amount added
313      * @throws NullPointerException if the date is null
314      */
315     public static Date addWeeks(final Date date, final int amount) {
316         return add(date, Calendar.WEEK_OF_YEAR, amount);
317     }
318 
319     /**
320      * Adds a number of years to a date returning a new object.
321      * The original {@link Date} is unchanged.
322      *
323      * @param date  the date, not null
324      * @param amount  the amount to add, may be negative
325      * @return the new {@link Date} with the amount added
326      * @throws NullPointerException if the date is null
327      */
328     public static Date addYears(final Date date, final int amount) {
329         return add(date, Calendar.YEAR, amount);
330     }
331 
332     /**
333      * Gets a date ceiling, leaving the field specified as the most
334      * significant field.
335      *
336      * <p>For example, if you had the date-time of 28 Mar 2002
337      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
338      * 2002 14:00:00.000.  If this was passed with MONTH, it would
339      * return 1 Apr 2002 0:00:00.000.</p>
340      *
341      * @param calendar  the date to work with, not null
342      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
343      * @return the different ceil date, not null
344      * @throws NullPointerException if the date is {@code null}
345      * @throws ArithmeticException if the year is over 280 million
346      * @since 2.5
347      */
348     public static Calendar ceiling(final Calendar calendar, final int field) {
349         Objects.requireNonNull(calendar, "calendar");
350         return modify((Calendar) calendar.clone(), field, ModifyType.CEILING);
351     }
352 
353     /**
354      * Gets a date ceiling, leaving the field specified as the most
355      * significant field.
356      *
357      * <p>For example, if you had the date-time of 28 Mar 2002
358      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
359      * 2002 14:00:00.000.  If this was passed with MONTH, it would
360      * return 1 Apr 2002 0:00:00.000.</p>
361      *
362      * @param date  the date to work with, not null
363      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
364      * @return the different ceil date, not null
365      * @throws NullPointerException if the date is {@code null}
366      * @throws ArithmeticException if the year is over 280 million
367      * @since 2.5
368      */
369     public static Date ceiling(final Date date, final int field) {
370         return modify(toCalendar(date), field, ModifyType.CEILING).getTime();
371     }
372 
373     /**
374      * Gets a date ceiling, leaving the field specified as the most
375      * significant field.
376      *
377      * <p>For example, if you had the date-time of 28 Mar 2002
378      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
379      * 2002 14:00:00.000.  If this was passed with MONTH, it would
380      * return 1 Apr 2002 0:00:00.000.</p>
381      *
382      * @param date  the date to work with, either {@link Date} or {@link Calendar}, not null
383      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
384      * @return the different ceil date, not null
385      * @throws NullPointerException if the date is {@code null}
386      * @throws ClassCastException if the object type is not a {@link Date} or {@link Calendar}
387      * @throws ArithmeticException if the year is over 280 million
388      * @since 2.5
389      */
390     public static Date ceiling(final Object date, final int field) {
391         Objects.requireNonNull(date, "date");
392         if (date instanceof Date) {
393             return ceiling((Date) date, field);
394         }
395         if (date instanceof Calendar) {
396             return ceiling((Calendar) date, field).getTime();
397         }
398         throw new ClassCastException("Could not find ceiling of for type: " + date.getClass());
399     }
400 
401     /**
402      * Gets a Calendar fragment for any unit.
403      *
404      * @param calendar the calendar to work with, not null
405      * @param fragment the Calendar field part of calendar to calculate
406      * @param unit the time unit
407      * @return number of units within the fragment of the calendar
408      * @throws NullPointerException if the date is {@code null} or
409      * fragment is not supported
410      * @since 2.4
411      */
412     private static long getFragment(final Calendar calendar, final int fragment, final TimeUnit unit) {
413         Objects.requireNonNull(calendar, "calendar");
414         long result = 0;
415         final int offset = unit == TimeUnit.DAYS ? 0 : 1;
416 
417         // Fragments bigger than a day require a breakdown to days
418         switch (fragment) {
419             case Calendar.YEAR:
420                 result += unit.convert(calendar.get(Calendar.DAY_OF_YEAR) - offset, TimeUnit.DAYS);
421                 break;
422             case Calendar.MONTH:
423                 result += unit.convert(calendar.get(Calendar.DAY_OF_MONTH) - offset, TimeUnit.DAYS);
424                 break;
425             default:
426                 break;
427         }
428 
429         switch (fragment) {
430             // Number of days already calculated for these cases
431             case Calendar.YEAR:
432             case Calendar.MONTH:
433 
434             // The rest of the valid cases
435             case Calendar.DAY_OF_YEAR:
436             case Calendar.DATE:
437                 result += unit.convert(calendar.get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS);
438                 // falls-through
439             case Calendar.HOUR_OF_DAY:
440                 result += unit.convert(calendar.get(Calendar.MINUTE), TimeUnit.MINUTES);
441                 // falls-through
442             case Calendar.MINUTE:
443                 result += unit.convert(calendar.get(Calendar.SECOND), TimeUnit.SECONDS);
444                 // falls-through
445             case Calendar.SECOND:
446                 result += unit.convert(calendar.get(Calendar.MILLISECOND), TimeUnit.MILLISECONDS);
447                 break;
448             case Calendar.MILLISECOND: break; //never useful
449                 default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
450         }
451         return result;
452     }
453 
454     /**
455      * Gets a Date fragment for any unit.
456      *
457      * @param date the date to work with, not null
458      * @param fragment the Calendar field part of date to calculate
459      * @param unit the time unit
460      * @return number of units within the fragment of the date
461      * @throws NullPointerException if the date is {@code null}
462      * @throws IllegalArgumentException if fragment is not supported
463      * @since 2.4
464      */
465     private static long getFragment(final Date date, final int fragment, final TimeUnit unit) {
466         validateDateNotNull(date);
467         final Calendar calendar = Calendar.getInstance();
468         calendar.setTime(date);
469         return getFragment(calendar, fragment, unit);
470     }
471 
472     /**
473      * Gets the number of days within the
474      * fragment. All datefields greater than the fragment will be ignored.
475      *
476      * <p>Asking the days of any date will only return the number of days
477      * of the current month (resulting in a number between 1 and 31). This
478      * method will retrieve the number of days for any fragment.
479      * For example, if you want to calculate the number of days past this year,
480      * your fragment is Calendar.YEAR. The result will be all days of the
481      * past month(s).</p>
482      *
483      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
484      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
485      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
486      * A fragment less than or equal to a DAY field will return 0.</p>
487      *
488      * <ul>
489      *  <li>January 28, 2008 with Calendar.MONTH as fragment will return 28
490      *   (equivalent to calendar.get(Calendar.DAY_OF_MONTH))</li>
491      *  <li>February 28, 2008 with Calendar.MONTH as fragment will return 28
492      *   (equivalent to calendar.get(Calendar.DAY_OF_MONTH))</li>
493      *  <li>January 28, 2008 with Calendar.YEAR as fragment will return 28
494      *   (equivalent to calendar.get(Calendar.DAY_OF_YEAR))</li>
495      *  <li>February 28, 2008 with Calendar.YEAR as fragment will return 59
496      *   (equivalent to calendar.get(Calendar.DAY_OF_YEAR))</li>
497      *  <li>January 28, 2008 with Calendar.MILLISECOND as fragment will return 0
498      *   (a millisecond cannot be split in days)</li>
499      * </ul>
500      *
501      * @param calendar the calendar to work with, not null
502      * @param fragment the {@link Calendar} field part of calendar to calculate
503      * @return number of days within the fragment of date
504      * @throws NullPointerException if the date is {@code null} or
505      * fragment is not supported
506      * @since 2.4
507      */
508     public static long getFragmentInDays(final Calendar calendar, final int fragment) {
509         return getFragment(calendar, fragment, TimeUnit.DAYS);
510     }
511 
512     /**
513      * Gets the number of days within the
514      * fragment. All date fields greater than the fragment will be ignored.
515      *
516      * <p>Asking the days of any date will only return the number of days
517      * of the current month (resulting in a number between 1 and 31). This
518      * method will retrieve the number of days for any fragment.
519      * For example, if you want to calculate the number of days past this year,
520      * your fragment is Calendar.YEAR. The result will be all days of the
521      * past month(s).</p>
522      *
523      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
524      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
525      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
526      * A fragment less than or equal to a DAY field will return 0.</p>
527      *
528      * <ul>
529      *  <li>January 28, 2008 with Calendar.MONTH as fragment will return 28
530      *   (equivalent to deprecated date.getDay())</li>
531      *  <li>February 28, 2008 with Calendar.MONTH as fragment will return 28
532      *   (equivalent to deprecated date.getDay())</li>
533      *  <li>January 28, 2008 with Calendar.YEAR as fragment will return 28</li>
534      *  <li>February 28, 2008 with Calendar.YEAR as fragment will return 59</li>
535      *  <li>January 28, 2008 with Calendar.MILLISECOND as fragment will return 0
536      *   (a millisecond cannot be split in days)</li>
537      * </ul>
538      *
539      * @param date the date to work with, not null
540      * @param fragment the {@link Calendar} field part of date to calculate
541      * @return number of days  within the fragment of date
542      * @throws NullPointerException if the date is {@code null}
543      * @throws IllegalArgumentException if the fragment is not supported
544      * @since 2.4
545      */
546     public static long getFragmentInDays(final Date date, final int fragment) {
547         return getFragment(date, fragment, TimeUnit.DAYS);
548     }
549 
550     /**
551      * Gets the number of hours within the
552      * fragment. All date fields greater than the fragment will be ignored.
553      *
554      * <p>Asking the hours of any date will only return the number of hours
555      * of the current day (resulting in a number between 0 and 23). This
556      * method will retrieve the number of hours for any fragment.
557      * For example, if you want to calculate the number of hours past this month,
558      * your fragment is Calendar.MONTH. The result will be all hours of the
559      * past day(s).</p>
560      *
561      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
562      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
563      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
564      * A fragment less than or equal to a HOUR field will return 0.</p>
565      *
566      * <ul>
567      *  <li>January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
568      *   (equivalent to calendar.get(Calendar.HOUR_OF_DAY))</li>
569      *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
570      *   (equivalent to calendar.get(Calendar.HOUR_OF_DAY))</li>
571      *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7</li>
572      *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)</li>
573      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
574      *   (a millisecond cannot be split in hours)</li>
575      * </ul>
576      *
577      * @param calendar the calendar to work with, not null
578      * @param fragment the {@link Calendar} field part of calendar to calculate
579      * @return number of hours within the fragment of date
580      * @throws NullPointerException if the date is {@code null} or
581      * fragment is not supported
582      * @since 2.4
583      */
584     public static long getFragmentInHours(final Calendar calendar, final int fragment) {
585         return getFragment(calendar, fragment, TimeUnit.HOURS);
586     }
587 
588     /**
589      * Gets the number of hours within the
590      * fragment. All date fields greater than the fragment will be ignored.
591      *
592      * <p>Asking the hours of any date will only return the number of hours
593      * of the current day (resulting in a number between 0 and 23). This
594      * method will retrieve the number of hours for any fragment.
595      * For example, if you want to calculate the number of hours past this month,
596      * your fragment is Calendar.MONTH. The result will be all hours of the
597      * past day(s).</p>
598      *
599      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
600      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
601      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
602      * A fragment less than or equal to a HOUR field will return 0.</p>
603      *
604      * <ul>
605      *  <li>January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
606      *   (equivalent to deprecated date.getHours())</li>
607      *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7
608      *   (equivalent to deprecated date.getHours())</li>
609      *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7</li>
610      *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)</li>
611      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
612      *   (a millisecond cannot be split in hours)</li>
613      * </ul>
614      *
615      * @param date the date to work with, not null
616      * @param fragment the {@link Calendar} field part of date to calculate
617      * @return number of hours within the fragment of date
618      * @throws NullPointerException if the date is {@code null}
619      * @throws IllegalArgumentException if the fragment is not supported
620      * @since 2.4
621      */
622     public static long getFragmentInHours(final Date date, final int fragment) {
623         return getFragment(date, fragment, TimeUnit.HOURS);
624     }
625 
626     /**
627      * Gets the number of milliseconds within the
628      * fragment. All date fields greater than the fragment will be ignored.
629      *
630      * <p>Asking the milliseconds of any date will only return the number of milliseconds
631      * of the current second (resulting in a number between 0 and 999). This
632      * method will retrieve the number of milliseconds for any fragment.
633      * For example, if you want to calculate the number of seconds past today,
634      * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
635      * be all seconds of the past hour(s), minutes(s) and second(s).</p>
636      *
637      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
638      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
639      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
640      * A fragment less than or equal to a MILLISECOND field will return 0.</p>
641      *
642      * <ul>
643      *  <li>January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
644      *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
645      *  <li>January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
646      *   (equivalent to calendar.get(Calendar.MILLISECOND))</li>
647      *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538
648      *   (10*1000 + 538)</li>
649      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
650      *   (a millisecond cannot be split in milliseconds)</li>
651      * </ul>
652      *
653      * @param calendar the calendar to work with, not null
654      * @param fragment the {@link Calendar} field part of calendar to calculate
655      * @return number of milliseconds within the fragment of date
656      * @throws NullPointerException if the date is {@code null} or
657      * fragment is not supported
658      * @since 2.4
659      */
660   public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) {
661     return getFragment(calendar, fragment, TimeUnit.MILLISECONDS);
662   }
663 
664     /**
665      * Gets the number of milliseconds within the
666      * fragment. All date fields greater than the fragment will be ignored.
667      *
668      * <p>Asking the milliseconds of any date will only return the number of milliseconds
669      * of the current second (resulting in a number between 0 and 999). This
670      * method will retrieve the number of milliseconds for any fragment.
671      * For example, if you want to calculate the number of milliseconds past today,
672      * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
673      * be all milliseconds of the past hour(s), minutes(s) and second(s).</p>
674      *
675      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
676      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
677      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
678      * A fragment less than or equal to a SECOND field will return 0.</p>
679      *
680      * <ul>
681      *  <li>January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538</li>
682      *  <li>January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538</li>
683      *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538 (10*1000 + 538)</li>
684      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
685      *   (a millisecond cannot be split in milliseconds)</li>
686      * </ul>
687      *
688      * @param date the date to work with, not null
689      * @param fragment the {@link Calendar} field part of date to calculate
690      * @return number of milliseconds within the fragment of date
691      * @throws NullPointerException if the date is {@code null}
692      * @throws IllegalArgumentException if the fragment is not supported
693      * @since 2.4
694      */
695     public static long getFragmentInMilliseconds(final Date date, final int fragment) {
696         return getFragment(date, fragment, TimeUnit.MILLISECONDS);
697     }
698 
699     /**
700      * Gets the number of minutes within the
701      * fragment. All date fields greater than the fragment will be ignored.
702      *
703      * <p>Asking the minutes of any date will only return the number of minutes
704      * of the current hour (resulting in a number between 0 and 59). This
705      * method will retrieve the number of minutes for any fragment.
706      * For example, if you want to calculate the number of minutes past this month,
707      * your fragment is Calendar.MONTH. The result will be all minutes of the
708      * past day(s) and hour(s).</p>
709      *
710      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
711      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
712      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
713      * A fragment less than or equal to a MINUTE field will return 0.</p>
714      *
715      * <ul>
716      *  <li>January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
717      *   (equivalent to calendar.get(Calendar.MINUTES))</li>
718      *  <li>January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
719      *   (equivalent to calendar.get(Calendar.MINUTES))</li>
720      *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15</li>
721      *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)</li>
722      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
723      *   (a millisecond cannot be split in minutes)</li>
724      * </ul>
725      *
726      * @param calendar the calendar to work with, not null
727      * @param fragment the {@link Calendar} field part of calendar to calculate
728      * @return number of minutes within the fragment of date
729      * @throws NullPointerException if the date is {@code null} or
730      * fragment is not supported
731      * @since 2.4
732      */
733     public static long getFragmentInMinutes(final Calendar calendar, final int fragment) {
734         return getFragment(calendar, fragment, TimeUnit.MINUTES);
735     }
736 
737     /**
738      * Gets the number of minutes within the
739      * fragment. All date fields greater than the fragment will be ignored.
740      *
741      * <p>Asking the minutes of any date will only return the number of minutes
742      * of the current hour (resulting in a number between 0 and 59). This
743      * method will retrieve the number of minutes for any fragment.
744      * For example, if you want to calculate the number of minutes past this month,
745      * your fragment is Calendar.MONTH. The result will be all minutes of the
746      * past day(s) and hour(s).</p>
747      *
748      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
749      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
750      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
751      * A fragment less than or equal to a MINUTE field will return 0.</p>
752      *
753      * <ul>
754      *  <li>January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
755      *   (equivalent to deprecated date.getMinutes())</li>
756      *  <li>January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15
757      *   (equivalent to deprecated date.getMinutes())</li>
758      *  <li>January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15</li>
759      *  <li>January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)</li>
760      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
761      *   (a millisecond cannot be split in minutes)</li>
762      * </ul>
763      *
764      * @param date the date to work with, not null
765      * @param fragment the {@link Calendar} field part of date to calculate
766      * @return number of minutes within the fragment of date
767      * @throws NullPointerException if the date is {@code null}
768      * @throws IllegalArgumentException if the fragment is not supported
769      * @since 2.4
770      */
771     public static long getFragmentInMinutes(final Date date, final int fragment) {
772         return getFragment(date, fragment, TimeUnit.MINUTES);
773     }
774 
775     /**
776      * Gets the number of seconds within the
777      * fragment. All date fields greater than the fragment will be ignored.
778      *
779      * <p>Asking the seconds of any date will only return the number of seconds
780      * of the current minute (resulting in a number between 0 and 59). This
781      * method will retrieve the number of seconds for any fragment.
782      * For example, if you want to calculate the number of seconds past today,
783      * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
784      * be all seconds of the past hour(s) and minutes(s).</p>
785      *
786      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
787      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
788      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
789      * A fragment less than or equal to a SECOND field will return 0.</p>
790      *
791      * <ul>
792      *  <li>January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
793      *   (equivalent to calendar.get(Calendar.SECOND))</li>
794      *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
795      *   (equivalent to calendar.get(Calendar.SECOND))</li>
796      *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110
797      *   (7*3600 + 15*60 + 10)</li>
798      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
799      *   (a millisecond cannot be split in seconds)</li>
800      * </ul>
801      *
802      * @param calendar the calendar to work with, not null
803      * @param fragment the {@link Calendar} field part of calendar to calculate
804      * @return number of seconds within the fragment of date
805      * @throws NullPointerException if the date is {@code null} or
806      * fragment is not supported
807      * @since 2.4
808      */
809     public static long getFragmentInSeconds(final Calendar calendar, final int fragment) {
810         return getFragment(calendar, fragment, TimeUnit.SECONDS);
811     }
812 
813     /**
814      * Gets the number of seconds within the
815      * fragment. All date fields greater than the fragment will be ignored.
816      *
817      * <p>Asking the seconds of any date will only return the number of seconds
818      * of the current minute (resulting in a number between 0 and 59). This
819      * method will retrieve the number of seconds for any fragment.
820      * For example, if you want to calculate the number of seconds past today,
821      * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will
822      * be all seconds of the past hour(s) and minutes(s).</p>
823      *
824      * <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both
825      * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY,
826      * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND
827      * A fragment less than or equal to a SECOND field will return 0.</p>
828      *
829      * <ul>
830      *  <li>January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
831      *   (equivalent to deprecated date.getSeconds())</li>
832      *  <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10
833      *   (equivalent to deprecated date.getSeconds())</li>
834      *  <li>January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110
835      *   (7*3600 + 15*60 + 10)</li>
836      *  <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0
837      *   (a millisecond cannot be split in seconds)</li>
838      * </ul>
839      *
840      * @param date the date to work with, not null
841      * @param fragment the {@link Calendar} field part of date to calculate
842      * @return number of seconds within the fragment of date
843      * @throws NullPointerException if the date is {@code null}
844      * @throws IllegalArgumentException if the fragment is not supported
845      * @since 2.4
846      */
847     public static long getFragmentInSeconds(final Date date, final int fragment) {
848         return getFragment(date, fragment, TimeUnit.SECONDS);
849     }
850 
851     /**
852      * Tests whether two calendar objects are on the same day ignoring time.
853      *
854      * <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
855      * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
856      * </p>
857      *
858      * @param cal1  the first calendar, not altered, not null
859      * @param cal2  the second calendar, not altered, not null
860      * @return true if they represent the same day
861      * @throws NullPointerException if either calendar is {@code null}
862      * @since 2.1
863      */
864     public static boolean isSameDay(final Calendar cal1, final Calendar cal2) {
865         Objects.requireNonNull(cal1, "cal1");
866         Objects.requireNonNull(cal2, "cal2");
867         return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
868                 cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
869                 cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
870     }
871 
872     /**
873      * Tests whether two date objects are on the same day ignoring time.
874      *
875      * <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
876      * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
877      * </p>
878      *
879      * @param date1  the first date, not altered, not null
880      * @param date2  the second date, not altered, not null
881      * @return true if they represent the same day
882      * @throws NullPointerException if either date is {@code null}
883      * @since 2.1
884      */
885     public static boolean isSameDay(final Date date1, final Date date2) {
886         return isSameDay(toCalendar(date1), toCalendar(date2));
887     }
888 
889     /**
890      * Tests whether two calendar objects represent the same instant in time.
891      *
892      * <p>This method compares the long millisecond time of the two objects.</p>
893      *
894      * @param cal1  the first calendar, not altered, not null
895      * @param cal2  the second calendar, not altered, not null
896      * @return true if they represent the same millisecond instant
897      * @throws NullPointerException if either date is {@code null}
898      * @since 2.1
899      */
900     public static boolean isSameInstant(final Calendar cal1, final Calendar cal2) {
901         Objects.requireNonNull(cal1, "cal1");
902         Objects.requireNonNull(cal2, "cal2");
903         return cal1.getTime().getTime() == cal2.getTime().getTime();
904     }
905 
906     /**
907      * Tests whether two date objects represent the same instant in time.
908      *
909      * <p>This method compares the long millisecond time of the two objects.</p>
910      *
911      * @param date1  the first date, not altered, not null
912      * @param date2  the second date, not altered, not null
913      * @return true if they represent the same millisecond instant
914      * @throws NullPointerException if either date is {@code null}
915      * @since 2.1
916      */
917     public static boolean isSameInstant(final Date date1, final Date date2) {
918         Objects.requireNonNull(date1, "date1");
919         Objects.requireNonNull(date2, "date2");
920         return date1.getTime() == date2.getTime();
921     }
922 
923     /**
924      * Tests whether two calendar objects represent the same local time.
925      *
926      * <p>This method compares the values of the fields of the two objects.
927      * In addition, both calendars must be the same of the same type.</p>
928      *
929      * @param cal1  the first calendar, not altered, not null
930      * @param cal2  the second calendar, not altered, not null
931      * @return true if they represent the same millisecond instant
932      * @throws NullPointerException if either date is {@code null}
933      * @since 2.1
934      */
935     public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) {
936         Objects.requireNonNull(cal1, "cal1");
937         Objects.requireNonNull(cal2, "cal2");
938         return cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
939                 cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
940                 cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
941                 cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) &&
942                 cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
943                 cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
944                 cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
945                 cal1.getClass() == cal2.getClass();
946     }
947 
948     /**
949      * Constructs an {@link Iterator} over each day in a date
950      * range defined by a focus date and range style.
951      *
952      * <p>For instance, passing Thursday, July 4, 2002 and a
953      * {@code RANGE_MONTH_SUNDAY} will return an {@link Iterator}
954      * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
955      * 2002, returning a Calendar instance for each intermediate day.</p>
956      *
957      * <p>This method provides an iterator that returns Calendar objects.
958      * The days are progressed using {@link Calendar#add(int, int)}.</p>
959      *
960      * @param calendar  the date to work with, not null
961      * @param rangeStyle  the style constant to use. Must be one of
962      * {@link DateUtils#RANGE_MONTH_SUNDAY},
963      * {@link DateUtils#RANGE_MONTH_MONDAY},
964      * {@link DateUtils#RANGE_WEEK_SUNDAY},
965      * {@link DateUtils#RANGE_WEEK_MONDAY},
966      * {@link DateUtils#RANGE_WEEK_RELATIVE},
967      * {@link DateUtils#RANGE_WEEK_CENTER}
968      * @return the date iterator, not null
969      * @throws NullPointerException if calendar is {@code null}
970      * @throws IllegalArgumentException if the rangeStyle is invalid
971      */
972     public static Iterator<Calendar> iterator(final Calendar calendar, final int rangeStyle) {
973         Objects.requireNonNull(calendar, "calendar");
974         final Calendar start;
975         final Calendar end;
976         int startCutoff = Calendar.SUNDAY;
977         int endCutoff = Calendar.SATURDAY;
978         switch (rangeStyle) {
979             case RANGE_MONTH_SUNDAY:
980             case RANGE_MONTH_MONDAY:
981                 //Set start to the first of the month
982                 start = truncate(calendar, Calendar.MONTH);
983                 //Set end to the last of the month
984                 end = (Calendar) start.clone();
985                 end.add(Calendar.MONTH, 1);
986                 end.add(Calendar.DATE, -1);
987                 //Loop start back to the previous sunday or monday
988                 if (rangeStyle == RANGE_MONTH_MONDAY) {
989                     startCutoff = Calendar.MONDAY;
990                     endCutoff = Calendar.SUNDAY;
991                 }
992                 break;
993             case RANGE_WEEK_SUNDAY:
994             case RANGE_WEEK_MONDAY:
995             case RANGE_WEEK_RELATIVE:
996             case RANGE_WEEK_CENTER:
997                 //Set start and end to the current date
998                 start = truncate(calendar, Calendar.DATE);
999                 end = truncate(calendar, Calendar.DATE);
1000                 switch (rangeStyle) {
1001                     case RANGE_WEEK_SUNDAY:
1002                         //already set by default
1003                         break;
1004                     case RANGE_WEEK_MONDAY:
1005                         startCutoff = Calendar.MONDAY;
1006                         endCutoff = Calendar.SUNDAY;
1007                         break;
1008                     case RANGE_WEEK_RELATIVE:
1009                         startCutoff = calendar.get(Calendar.DAY_OF_WEEK);
1010                         endCutoff = startCutoff - 1;
1011                         break;
1012                     case RANGE_WEEK_CENTER:
1013                         startCutoff = calendar.get(Calendar.DAY_OF_WEEK) - 3;
1014                         endCutoff = calendar.get(Calendar.DAY_OF_WEEK) + 3;
1015                         break;
1016                     default:
1017                         break;
1018                 }
1019                 break;
1020             default:
1021                 throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
1022         }
1023         if (startCutoff < Calendar.SUNDAY) {
1024             startCutoff += 7;
1025         }
1026         if (startCutoff > Calendar.SATURDAY) {
1027             startCutoff -= 7;
1028         }
1029         if (endCutoff < Calendar.SUNDAY) {
1030             endCutoff += 7;
1031         }
1032         if (endCutoff > Calendar.SATURDAY) {
1033             endCutoff -= 7;
1034         }
1035         while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
1036             start.add(Calendar.DATE, -1);
1037         }
1038         while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
1039             end.add(Calendar.DATE, 1);
1040         }
1041         return new DateIterator(start, end);
1042     }
1043 
1044     /**
1045      * Constructs an {@link Iterator} over each day in a date
1046      * range defined by a focus date and range style.
1047      *
1048      * <p>For instance, passing Thursday, July 4, 2002 and a
1049      * {@code RANGE_MONTH_SUNDAY} will return an {@link Iterator}
1050      * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
1051      * 2002, returning a Calendar instance for each intermediate day.</p>
1052      *
1053      * <p>This method provides an iterator that returns Calendar objects.
1054      * The days are progressed using {@link Calendar#add(int, int)}.</p>
1055      *
1056      * @param focus  the date to work with, not null
1057      * @param rangeStyle  the style constant to use. Must be one of
1058      * {@link DateUtils#RANGE_MONTH_SUNDAY},
1059      * {@link DateUtils#RANGE_MONTH_MONDAY},
1060      * {@link DateUtils#RANGE_WEEK_SUNDAY},
1061      * {@link DateUtils#RANGE_WEEK_MONDAY},
1062      * {@link DateUtils#RANGE_WEEK_RELATIVE},
1063      * {@link DateUtils#RANGE_WEEK_CENTER}
1064      * @return the date iterator, not null, not null
1065      * @throws NullPointerException if the date is {@code null}
1066      * @throws IllegalArgumentException if the rangeStyle is invalid
1067      */
1068     public static Iterator<Calendar> iterator(final Date focus, final int rangeStyle) {
1069         return iterator(toCalendar(focus), rangeStyle);
1070     }
1071 
1072     /**
1073      * Constructs an {@link Iterator} over each day in a date
1074      * range defined by a focus date and range style.
1075      *
1076      * <p>For instance, passing Thursday, July 4, 2002 and a
1077      * {@code RANGE_MONTH_SUNDAY} will return an {@link Iterator}
1078      * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
1079      * 2002, returning a Calendar instance for each intermediate day.</p>
1080      *
1081      * @param calendar  the date to work with, either {@link Date} or {@link Calendar}, not null
1082      * @param rangeStyle  the style constant to use. Must be one of the range
1083      * styles listed for the {@link #iterator(Calendar, int)} method.
1084      * @return the date iterator, not null
1085      * @throws NullPointerException if the date is {@code null}
1086      * @throws ClassCastException if the object type is not a {@link Date} or {@link Calendar}
1087      */
1088     public static Iterator<?> iterator(final Object calendar, final int rangeStyle) {
1089         Objects.requireNonNull(calendar, "calendar");
1090         if (calendar instanceof Date) {
1091             return iterator((Date) calendar, rangeStyle);
1092         }
1093         if (calendar instanceof Calendar) {
1094             return iterator((Calendar) calendar, rangeStyle);
1095         }
1096         throw new ClassCastException("Could not iterate based on " + calendar);
1097     }
1098 
1099     /**
1100      * Internal calculation method.
1101      *
1102      * @param val  the calendar, not null
1103      * @param field  the field constant
1104      * @param modType  type to truncate, round or ceiling
1105      * @return the given calendar
1106      * @throws ArithmeticException if the year is over 280 million
1107      */
1108     private static Calendar modify(final Calendar val, final int field, final ModifyType modType) {
1109         if (val.get(Calendar.YEAR) > 280000000) {
1110             throw new ArithmeticException("Calendar value too large for accurate calculations");
1111         }
1112 
1113         if (field == Calendar.MILLISECOND) {
1114             return val;
1115         }
1116 
1117         // Fix for LANG-59 START
1118         // see https://issues.apache.org/jira/browse/LANG-59
1119         //
1120         // Manually truncate milliseconds, seconds and minutes, rather than using
1121         // Calendar methods.
1122 
1123         final Date date = val.getTime();
1124         long time = date.getTime();
1125         boolean done = false;
1126 
1127         // truncate milliseconds
1128         final int millisecs = val.get(Calendar.MILLISECOND);
1129         if (ModifyType.TRUNCATE == modType || millisecs < 500) {
1130             time -= millisecs;
1131         }
1132         if (field == Calendar.SECOND) {
1133             done = true;
1134         }
1135 
1136         // truncate seconds
1137         final int seconds = val.get(Calendar.SECOND);
1138         if (!done && (ModifyType.TRUNCATE == modType || seconds < 30)) {
1139             time = time - seconds * 1000L;
1140         }
1141         if (field == Calendar.MINUTE) {
1142             done = true;
1143         }
1144 
1145         // truncate minutes
1146         final int minutes = val.get(Calendar.MINUTE);
1147         if (!done && (ModifyType.TRUNCATE == modType || minutes < 30)) {
1148             time = time - minutes * 60000L;
1149         }
1150 
1151         // reset time
1152         if (date.getTime() != time) {
1153             date.setTime(time);
1154             val.setTime(date);
1155         }
1156         // Fix for LANG-59 END
1157 
1158         boolean roundUp = false;
1159         for (final int[] aField : fields) {
1160             for (final int element : aField) {
1161                 if (element == field) {
1162                     //This is our field... we stop looping
1163                     if (modType == ModifyType.CEILING || modType == ModifyType.ROUND && roundUp) {
1164                         if (field == SEMI_MONTH) {
1165                             //This is a special case that's hard to generalize
1166                             //If the date is 1, we round up to 16, otherwise
1167                             //  we subtract 15 days and add 1 month
1168                             if (val.get(Calendar.DATE) == 1) {
1169                                 val.add(Calendar.DATE, 15);
1170                             } else {
1171                                 val.add(Calendar.DATE, -15);
1172                                 val.add(Calendar.MONTH, 1);
1173                             }
1174                         // Fix for LANG-440 START
1175                         } else if (field == Calendar.AM_PM) {
1176                             // This is a special case
1177                             // If the time is 0, we round up to 12, otherwise
1178                             //  we subtract 12 hours and add 1 day
1179                             if (val.get(Calendar.HOUR_OF_DAY) == 0) {
1180                                 val.add(Calendar.HOUR_OF_DAY, 12);
1181                             } else {
1182                                 val.add(Calendar.HOUR_OF_DAY, -12);
1183                                 val.add(Calendar.DATE, 1);
1184                             }
1185                             // Fix for LANG-440 END
1186                         } else {
1187                             //We need at add one to this field since the
1188                             //  last number causes us to round up
1189                             val.add(aField[0], 1);
1190                         }
1191                     }
1192                     return val;
1193                 }
1194             }
1195             //We have various fields that are not easy roundings
1196             int offset = 0;
1197             boolean offsetSet = false;
1198             //These are special types of fields that require different rounding rules
1199             switch (field) {
1200                 case SEMI_MONTH:
1201                     if (aField[0] == Calendar.DATE) {
1202                         //If we're going to drop the DATE field's value,
1203                         //  we want to do this our own way.
1204                         //We need to subtract 1 since the date has a minimum of 1
1205                         offset = val.get(Calendar.DATE) - 1;
1206                         //If we're above 15 days adjustment, that means we're in the
1207                         //  bottom half of the month and should stay accordingly.
1208                         if (offset >= 15) {
1209                             offset -= 15;
1210                         }
1211                         //Record whether we're in the top or bottom half of that range
1212                         roundUp = offset > 7;
1213                         offsetSet = true;
1214                     }
1215                     break;
1216                 case Calendar.AM_PM:
1217                     if (aField[0] == Calendar.HOUR_OF_DAY) {
1218                         //If we're going to drop the HOUR field's value,
1219                         //  we want to do this our own way.
1220                         offset = val.get(Calendar.HOUR_OF_DAY);
1221                         if (offset >= 12) {
1222                             offset -= 12;
1223                         }
1224                         roundUp = offset >= 6;
1225                         offsetSet = true;
1226                     }
1227                     break;
1228                 default:
1229                     break;
1230             }
1231             if (!offsetSet) {
1232                 final int min = val.getActualMinimum(aField[0]);
1233                 final int max = val.getActualMaximum(aField[0]);
1234                 //Calculate the offset from the minimum allowed value
1235                 offset = val.get(aField[0]) - min;
1236                 //Set roundUp if this is more than halfway between the minimum and maximum
1237                 roundUp = offset > (max - min) / 2;
1238             }
1239             //We need to remove this field
1240             if (offset != 0) {
1241                 val.set(aField[0], val.get(aField[0]) - offset);
1242             }
1243         }
1244         throw new IllegalArgumentException("The field " + field + " is not supported");
1245     }
1246 
1247     /**
1248      * Parses a string representing a date by trying a variety of different parsers,
1249      * using the default date format symbols for the given locale.
1250      *
1251      * <p>The parse will try each parse pattern in turn.
1252      * A parse is only deemed successful if it parses the whole of the input string.
1253      * If no parse patterns match, a ParseException is thrown.</p>
1254      * The parser will be lenient toward the parsed date.
1255      *
1256      * @param str  the date to parse, not null
1257      * @param locale the locale whose date format symbols should be used. If {@code null},
1258      * the system locale is used (as per {@link #parseDate(String, String...)}).
1259      * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
1260      * @return the parsed date
1261      * @throws NullPointerException if the date string or pattern array is null
1262      * @throws ParseException if none of the date patterns were suitable (or there were none)
1263      * @since 3.2
1264      */
1265     public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) throws ParseException {
1266         return parseDateWithLeniency(str, locale, parsePatterns, true);
1267     }
1268 
1269     /**
1270      * Parses a string representing a date by trying a variety of different parsers.
1271      *
1272      * <p>The parse will try each parse pattern in turn.
1273      * A parse is only deemed successful if it parses the whole of the input string.
1274      * If no parse patterns match, a ParseException is thrown.</p>
1275      * The parser will be lenient toward the parsed date.
1276      *
1277      * @param str  the date to parse, not null
1278      * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
1279      * @return the parsed date
1280      * @throws NullPointerException if the date string or pattern array is null
1281      * @throws ParseException if none of the date patterns were suitable (or there were none)
1282      */
1283     public static Date parseDate(final String str, final String... parsePatterns) throws ParseException {
1284         return parseDate(str, null, parsePatterns);
1285     }
1286 
1287     /**
1288      * Parses a string representing a date by trying a variety of different parsers,
1289      * using the default date format symbols for the given locale.
1290      *
1291      * <p>The parse will try each parse pattern in turn.
1292      * A parse is only deemed successful if it parses the whole of the input string.
1293      * If no parse patterns match, a ParseException is thrown.</p>
1294      * The parser parses strictly - it does not allow for dates such as "February 942, 1996".
1295      *
1296      * @param str  the date to parse, not null
1297      * @param locale the locale whose date format symbols should be used. If {@code null},
1298      * the system locale is used (as per {@link #parseDateStrictly(String, String...)}).
1299      * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
1300      * @return the parsed date
1301      * @throws NullPointerException if the date string or pattern array is null
1302      * @throws ParseException if none of the date patterns were suitable
1303      * @since 3.2
1304      */
1305     public static Date parseDateStrictly(final String str, final Locale locale, final String... parsePatterns) throws ParseException {
1306         return parseDateWithLeniency(str, locale, parsePatterns, false);
1307     }
1308 
1309     /**
1310      * Parses a string representing a date by trying a variety of different parsers.
1311      *
1312      * <p>The parse will try each parse pattern in turn.
1313      * A parse is only deemed successful if it parses the whole of the input string.
1314      * If no parse patterns match, a ParseException is thrown.</p>
1315      * The parser parses strictly - it does not allow for dates such as "February 942, 1996".
1316      *
1317      * @param str  the date to parse, not null
1318      * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
1319      * @return the parsed date
1320      * @throws NullPointerException if the date string or pattern array is null
1321      * @throws ParseException if none of the date patterns were suitable
1322      * @since 2.5
1323      */
1324     public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException {
1325         return parseDateStrictly(str, null, parsePatterns);
1326     }
1327 
1328     /**
1329      * Parses a string representing a date by trying a variety of different parsers.
1330      *
1331      * <p>The parse will try each parse pattern in turn.
1332      * A parse is only deemed successful if it parses the whole of the input string.
1333      * If no parse patterns match, a ParseException is thrown.</p>
1334      *
1335      * @param dateStr  the date to parse, not null
1336      * @param locale the locale to use when interpreting the pattern, can be null in which
1337      * case the default system locale is used
1338      * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
1339      * @param lenient Specify whether or not date/time parsing is to be lenient.
1340      * @return the parsed date
1341      * @throws NullPointerException if the date string or pattern array is null
1342      * @throws ParseException if none of the date patterns were suitable
1343      * @see java.util.Calendar#isLenient()
1344      */
1345     private static Date parseDateWithLeniency(final String dateStr, final Locale locale, final String[] parsePatterns,
1346         final boolean lenient) throws ParseException {
1347         Objects.requireNonNull(dateStr, "str");
1348         Objects.requireNonNull(parsePatterns, "parsePatterns");
1349 
1350         final TimeZone tz = TimeZone.getDefault();
1351         final Locale lcl = LocaleUtils.toLocale(locale);
1352         final ParsePosition pos = new ParsePosition(0);
1353         final Calendar calendar = Calendar.getInstance(tz, lcl);
1354         calendar.setLenient(lenient);
1355 
1356         for (final String parsePattern : parsePatterns) {
1357             final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl);
1358             calendar.clear();
1359             try {
1360                 if (fdp.parse(dateStr, pos, calendar) && pos.getIndex() == dateStr.length()) {
1361                     return calendar.getTime();
1362                 }
1363             } catch (final IllegalArgumentException ignored) {
1364                 // leniency is preventing calendar from being set
1365             }
1366             pos.setIndex(0);
1367         }
1368         throw new ParseException("Unable to parse the date: " + dateStr, -1);
1369     }
1370 
1371     /**
1372      * Rounds a date, leaving the field specified as the most
1373      * significant field.
1374      *
1375      * <p>For example, if you had the date-time of 28 Mar 2002
1376      * 13:45:01.231, if this was passed with HOUR, it would return
1377      * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
1378      * would return 1 April 2002 0:00:00.000.</p>
1379      *
1380      * <p>For a date in a time zone that handles the change to daylight
1381      * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
1382      * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
1383      * date that crosses this time would produce the following values:
1384      * </p>
1385      * <ul>
1386      * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
1387      * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
1388      * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
1389      * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
1390      * </ul>
1391      *
1392      * @param calendar  the date to work with, not null
1393      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1394      * @return the different rounded date, not null
1395      * @throws NullPointerException if the date is {@code null}
1396      * @throws ArithmeticException if the year is over 280 million
1397      */
1398     public static Calendar round(final Calendar calendar, final int field) {
1399         Objects.requireNonNull(calendar, "calendar");
1400         return modify((Calendar) calendar.clone(), field, ModifyType.ROUND);
1401     }
1402 
1403     /**
1404      * Rounds a date, leaving the field specified as the most
1405      * significant field.
1406      *
1407      * <p>For example, if you had the date-time of 28 Mar 2002
1408      * 13:45:01.231, if this was passed with HOUR, it would return
1409      * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
1410      * would return 1 April 2002 0:00:00.000.</p>
1411      *
1412      * <p>For a date in a time zone that handles the change to daylight
1413      * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
1414      * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
1415      * date that crosses this time would produce the following values:
1416      * </p>
1417      * <ul>
1418      * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
1419      * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
1420      * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
1421      * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
1422      * </ul>
1423      *
1424      * @param date  the date to work with, not null
1425      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1426      * @return the different rounded date, not null
1427      * @throws NullPointerException if the date is null
1428      * @throws ArithmeticException if the year is over 280 million
1429      */
1430     public static Date round(final Date date, final int field) {
1431         return modify(toCalendar(date), field, ModifyType.ROUND).getTime();
1432     }
1433 
1434     /**
1435      * Rounds a date, leaving the field specified as the most
1436      * significant field.
1437      *
1438      * <p>For example, if you had the date-time of 28 Mar 2002
1439      * 13:45:01.231, if this was passed with HOUR, it would return
1440      * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
1441      * would return 1 April 2002 0:00:00.000.</p>
1442      *
1443      * <p>For a date in a time zone that handles the change to daylight
1444      * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
1445      * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
1446      * date that crosses this time would produce the following values:
1447      * </p>
1448      * <ul>
1449      * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
1450      * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
1451      * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
1452      * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
1453      * </ul>
1454      *
1455      * @param date  the date to work with, either {@link Date} or {@link Calendar}, not null
1456      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1457      * @return the different rounded date, not null
1458      * @throws NullPointerException if the date is {@code null}
1459      * @throws ClassCastException if the object type is not a {@link Date} or {@link Calendar}
1460      * @throws ArithmeticException if the year is over 280 million
1461      */
1462     public static Date round(final Object date, final int field) {
1463         Objects.requireNonNull(date, "date");
1464         if (date instanceof Date) {
1465             return round((Date) date, field);
1466         }
1467         if (date instanceof Calendar) {
1468             return round((Calendar) date, field).getTime();
1469         }
1470         throw new ClassCastException("Could not round " + date);
1471     }
1472 
1473     /**
1474      * Sets the specified field to a date returning a new object.
1475      * This does not use a lenient calendar.
1476      * The original {@link Date} is unchanged.
1477      *
1478      * @param date  the date, not null
1479      * @param calendarField  the {@link Calendar} field to set the amount to
1480      * @param amount the amount to set
1481      * @return a new {@link Date} set with the specified value
1482      * @throws NullPointerException if the date is null
1483      * @since 2.4
1484      */
1485     private static Date set(final Date date, final int calendarField, final int amount) {
1486         validateDateNotNull(date);
1487         // getInstance() returns a new object, so this method is thread safe.
1488         final Calendar c = Calendar.getInstance();
1489         c.setLenient(false);
1490         c.setTime(date);
1491         c.set(calendarField, amount);
1492         return c.getTime();
1493     }
1494 
1495     /**
1496      * Sets the day of month field to a date returning a new object.
1497      * The original {@link Date} is unchanged.
1498      *
1499      * @param date  the date, not null
1500      * @param amount the amount to set
1501      * @return a new {@link Date} set with the specified value
1502      * @throws NullPointerException if the date is null
1503      * @throws IllegalArgumentException if {@code amount} is not in the range
1504      *  {@code 1 <= amount <= 31}
1505      * @since 2.4
1506      */
1507     public static Date setDays(final Date date, final int amount) {
1508         return set(date, Calendar.DAY_OF_MONTH, amount);
1509     }
1510 
1511     /**
1512      * Sets the hours field to a date returning a new object.  Hours range
1513      * from  0-23.
1514      * The original {@link Date} is unchanged.
1515      *
1516      * @param date  the date, not null
1517      * @param amount the amount to set
1518      * @return a new {@link Date} set with the specified value
1519      * @throws NullPointerException if the date is null
1520      * @throws IllegalArgumentException if {@code amount} is not in the range
1521      *  {@code 0 <= amount <= 23}
1522      * @since 2.4
1523      */
1524     public static Date setHours(final Date date, final int amount) {
1525         return set(date, Calendar.HOUR_OF_DAY, amount);
1526     }
1527 
1528     /**
1529      * Sets the milliseconds field to a date returning a new object.
1530      * The original {@link Date} is unchanged.
1531      *
1532      * @param date  the date, not null
1533      * @param amount the amount to set
1534      * @return a new {@link Date} set with the specified value
1535      * @throws NullPointerException if the date is null
1536      * @throws IllegalArgumentException if {@code amount} is not in the range
1537      *  {@code 0 <= amount <= 999}
1538      * @since 2.4
1539      */
1540     public static Date setMilliseconds(final Date date, final int amount) {
1541         return set(date, Calendar.MILLISECOND, amount);
1542     }
1543 
1544     /**
1545      * Sets the minute field to a date returning a new object.
1546      * The original {@link Date} is unchanged.
1547      *
1548      * @param date  the date, not null
1549      * @param amount the amount to set
1550      * @return a new {@link Date} set with the specified value
1551      * @throws NullPointerException if the date is null
1552      * @throws IllegalArgumentException if {@code amount} is not in the range
1553      *  {@code 0 <= amount <= 59}
1554      * @since 2.4
1555      */
1556     public static Date setMinutes(final Date date, final int amount) {
1557         return set(date, Calendar.MINUTE, amount);
1558     }
1559 
1560     /**
1561      * Sets the months field to a date returning a new object.
1562      * The original {@link Date} is unchanged.
1563      *
1564      * @param date  the date, not null
1565      * @param amount the amount to set
1566      * @return a new {@link Date} set with the specified value
1567      * @throws NullPointerException if the date is null
1568      * @throws IllegalArgumentException if {@code amount} is not in the range
1569      *  {@code 0 <= amount <= 11}
1570      * @since 2.4
1571      */
1572     public static Date setMonths(final Date date, final int amount) {
1573         return set(date, Calendar.MONTH, amount);
1574     }
1575 
1576     /**
1577      * Sets the seconds field to a date returning a new object.
1578      * The original {@link Date} is unchanged.
1579      *
1580      * @param date  the date, not null
1581      * @param amount the amount to set
1582      * @return a new {@link Date} set with the specified value
1583      * @throws NullPointerException if the date is null
1584      * @throws IllegalArgumentException if {@code amount} is not in the range
1585      *  {@code 0 <= amount <= 59}
1586      * @since 2.4
1587      */
1588     public static Date setSeconds(final Date date, final int amount) {
1589         return set(date, Calendar.SECOND, amount);
1590     }
1591     /**
1592      * Sets the years field to a date returning a new object.
1593      * The original {@link Date} is unchanged.
1594      *
1595      * @param date  the date, not null
1596      * @param amount the amount to set
1597      * @return a new {@link Date} set with the specified value
1598      * @throws NullPointerException if the date is null
1599      * @since 2.4
1600      */
1601     public static Date setYears(final Date date, final int amount) {
1602         return set(date, Calendar.YEAR, amount);
1603     }
1604 
1605     /**
1606      * Converts a {@link Date} into a {@link Calendar}.
1607      *
1608      * @param date the date to convert to a Calendar
1609      * @return the created Calendar
1610      * @throws NullPointerException if null is passed in
1611      * @since 3.0
1612      */
1613     public static Calendar toCalendar(final Date date) {
1614         final Calendar c = Calendar.getInstance();
1615         c.setTime(Objects.requireNonNull(date, "date"));
1616         return c;
1617     }
1618 
1619     /**
1620      * Converts a {@link Date} of a given {@link TimeZone} into a {@link Calendar}.
1621      *
1622      * @param date the date to convert to a Calendar
1623      * @param tz the time zone of the {@code date}
1624      * @return the created Calendar
1625      * @throws NullPointerException if {@code date} or {@code tz} is null
1626      */
1627     public static Calendar toCalendar(final Date date, final TimeZone tz) {
1628         final Calendar c = Calendar.getInstance(tz);
1629         c.setTime(Objects.requireNonNull(date, "date"));
1630         return c;
1631     }
1632 
1633     /**
1634      * Converts a {@link Date} to a {@link LocalDateTime}.
1635      *
1636      * @param date the Date to convert, not null.
1637      * @return a new LocalDateTime.
1638      * @since 3.19.0
1639      */
1640     public static LocalDateTime toLocalDateTime(final Date date) {
1641         return toLocalDateTime(date, TimeZone.getDefault());
1642     }
1643 
1644     /**
1645      * Converts a {@link Date} to a {@link LocalDateTime}.
1646      *
1647      * @param date     the Date to convert to a LocalDateTime, not null.
1648      * @param timeZone the time zone, null maps to to the default time zone.
1649      * @return a new LocalDateTime.
1650      * @since 3.19.0
1651      */
1652     public static LocalDateTime toLocalDateTime(final Date date, final TimeZone timeZone) {
1653         return LocalDateTime.ofInstant(date.toInstant(), toZoneId(timeZone));
1654     }
1655 
1656     /**
1657      * Converts a {@link Date} to a {@link OffsetDateTime}.
1658      *
1659      * @param date the Date to convert, not null.
1660      * @return a new OffsetDateTime.
1661      * @since 3.19.0
1662      */
1663     public static OffsetDateTime toOffsetDateTime(final Date date) {
1664         return toOffsetDateTime(date, TimeZone.getDefault());
1665     }
1666 
1667     /**
1668      * Converts a {@link Date} to a {@link OffsetDateTime}.
1669      *
1670      * @param date     the Date to convert to a OffsetDateTime, not null.
1671      * @param timeZone the time zone, null maps to to the default time zone.
1672      * @return a new OffsetDateTime.
1673      * @since 3.19.0
1674      */
1675     public static OffsetDateTime toOffsetDateTime(final Date date, final TimeZone timeZone) {
1676         return OffsetDateTime.ofInstant(date.toInstant(), toZoneId(timeZone));
1677     }
1678 
1679     /**
1680      * Converts a {@link Date} to a {@link ZonedDateTime}.
1681      *
1682      * @param date the Date to convert, not null.
1683      * @return a new ZonedDateTime.
1684      * @since 3.19.0
1685      */
1686     public static ZonedDateTime toZonedDateTime(final Date date) {
1687         return toZonedDateTime(date, TimeZone.getDefault());
1688     }
1689 
1690     /**
1691      * Converts a {@link Date} to a {@link ZonedDateTime}.
1692      *
1693      * @param date     the Date to convert to a ZonedDateTime, not null.
1694      * @param timeZone the time zone, null maps to to the default time zone.
1695      * @return a new ZonedDateTime.
1696      * @since 3.19.0
1697      */
1698     public static ZonedDateTime toZonedDateTime(final Date date, final TimeZone timeZone) {
1699         return ZonedDateTime.ofInstant(date.toInstant(), toZoneId(timeZone));
1700     }
1701 
1702     private static ZoneId toZoneId(final TimeZone timeZone) {
1703         return TimeZones.toTimeZone(timeZone).toZoneId();
1704     }
1705 
1706     /**
1707      * Truncates a date, leaving the field specified as the most
1708      * significant field.
1709      *
1710      * <p>For example, if you had the date-time of 28 Mar 2002
1711      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
1712      * 2002 13:00:00.000.  If this was passed with MONTH, it would
1713      * return 1 Mar 2002 0:00:00.000.</p>
1714      *
1715      * @param date  the date to work with, not null
1716      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1717      * @return the different truncated date, not null
1718      * @throws NullPointerException if the date is {@code null}
1719      * @throws ArithmeticException if the year is over 280 million
1720      */
1721     public static Calendar truncate(final Calendar date, final int field) {
1722         Objects.requireNonNull(date, "date");
1723         return modify((Calendar) date.clone(), field, ModifyType.TRUNCATE);
1724     }
1725 
1726     /**
1727      * Truncates a date, leaving the field specified as the most
1728      * significant field.
1729      *
1730      * <p>For example, if you had the date-time of 28 Mar 2002
1731      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
1732      * 2002 13:00:00.000.  If this was passed with MONTH, it would
1733      * return 1 Mar 2002 0:00:00.000.</p>
1734      *
1735      * @param date  the date to work with, not null
1736      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1737      * @return the different truncated date, not null
1738      * @throws NullPointerException if the date is {@code null}
1739      * @throws ArithmeticException if the year is over 280 million
1740      */
1741     public static Date truncate(final Date date, final int field) {
1742         return modify(toCalendar(date), field, ModifyType.TRUNCATE).getTime();
1743     }
1744 
1745     /**
1746      * Truncates a date, leaving the field specified as the most
1747      * significant field.
1748      *
1749      * <p>For example, if you had the date-time of 28 Mar 2002
1750      * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
1751      * 2002 13:00:00.000.  If this was passed with MONTH, it would
1752      * return 1 Mar 2002 0:00:00.000.</p>
1753      *
1754      * @param date  the date to work with, either {@link Date} or {@link Calendar}, not null
1755      * @param field  the field from {@link Calendar} or {@code SEMI_MONTH}
1756      * @return the different truncated date, not null
1757      * @throws NullPointerException if the date is {@code null}
1758      * @throws ClassCastException if the object type is not a {@link Date} or {@link Calendar}
1759      * @throws ArithmeticException if the year is over 280 million
1760      */
1761     public static Date truncate(final Object date, final int field) {
1762         Objects.requireNonNull(date, "date");
1763         if (date instanceof Date) {
1764             return truncate((Date) date, field);
1765         }
1766         if (date instanceof Calendar) {
1767             return truncate((Calendar) date, field).getTime();
1768         }
1769         throw new ClassCastException("Could not truncate " + date);
1770     }
1771 
1772     /**
1773      * Determines how two calendars compare up to no more than the specified
1774      * most significant field.
1775      *
1776      * @param cal1 the first calendar, not {@code null}
1777      * @param cal2 the second calendar, not {@code null}
1778      * @param field the field from {@link Calendar}
1779      * @return a negative integer, zero, or a positive integer as the first
1780      * calendar is less than, equal to, or greater than the second.
1781      * @throws NullPointerException if any argument is {@code null}
1782      * @see #truncate(Calendar, int)
1783      * @see #truncatedCompareTo(Date, Date, int)
1784      * @since 3.0
1785      */
1786     public static int truncatedCompareTo(final Calendar cal1, final Calendar cal2, final int field) {
1787         final Calendar truncatedCal1 = truncate(cal1, field);
1788         final Calendar truncatedCal2 = truncate(cal2, field);
1789         return truncatedCal1.compareTo(truncatedCal2);
1790     }
1791 
1792     /**
1793      * Determines how two dates compare up to no more than the specified
1794      * most significant field.
1795      *
1796      * @param date1 the first date, not {@code null}
1797      * @param date2 the second date, not {@code null}
1798      * @param field the field from {@link Calendar}
1799      * @return a negative integer, zero, or a positive integer as the first
1800      * date is less than, equal to, or greater than the second.
1801      * @throws NullPointerException if any argument is {@code null}
1802      * @see #truncate(Calendar, int)
1803      * @see #truncatedCompareTo(Date, Date, int)
1804      * @since 3.0
1805      */
1806     public static int truncatedCompareTo(final Date date1, final Date date2, final int field) {
1807         final Date truncatedDate1 = truncate(date1, field);
1808         final Date truncatedDate2 = truncate(date2, field);
1809         return truncatedDate1.compareTo(truncatedDate2);
1810     }
1811 
1812     /**
1813      * Determines if two calendars are equal up to no more than the specified
1814      * most significant field.
1815      *
1816      * @param cal1 the first calendar, not {@code null}
1817      * @param cal2 the second calendar, not {@code null}
1818      * @param field the field from {@link Calendar}
1819      * @return {@code true} if equal; otherwise {@code false}
1820      * @throws NullPointerException if any argument is {@code null}
1821      * @see #truncate(Calendar, int)
1822      * @see #truncatedEquals(Date, Date, int)
1823      * @since 3.0
1824      */
1825     public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) {
1826         return truncatedCompareTo(cal1, cal2, field) == 0;
1827     }
1828 
1829     /**
1830      * Determines if two dates are equal up to no more than the specified
1831      * most significant field.
1832      *
1833      * @param date1 the first date, not {@code null}
1834      * @param date2 the second date, not {@code null}
1835      * @param field the field from {@link Calendar}
1836      * @return {@code true} if equal; otherwise {@code false}
1837      * @throws NullPointerException if any argument is {@code null}
1838      * @see #truncate(Date, int)
1839      * @see #truncatedEquals(Calendar, Calendar, int)
1840      * @since 3.0
1841      */
1842     public static boolean truncatedEquals(final Date date1, final Date date2, final int field) {
1843         return truncatedCompareTo(date1, date2, field) == 0;
1844     }
1845 
1846     /**
1847      * @param date Date to validate.
1848      * @throws NullPointerException if {@code date == null}
1849      */
1850     private static void validateDateNotNull(final Date date) {
1851         Objects.requireNonNull(date, "date");
1852     }
1853 
1854     /**
1855      * {@link DateUtils} instances should NOT be constructed in
1856      * standard programming. Instead, the static methods on the class should
1857      * be used, such as {@code DateUtils.parseDate(str);}.
1858      *
1859      * <p>This constructor is public to permit tools that require a JavaBean
1860      * instance to operate.</p>
1861      *
1862      * @deprecated TODO Make private in 4.0.
1863      */
1864     @Deprecated
1865     public DateUtils() {
1866         // empty
1867     }
1868 
1869 }