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