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