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