View Javadoc
1   // %1117664764859:hoplugins.commons.utils%
2   package hoplugins.commons.utils;
3   
4   import java.util.Calendar;
5   import java.util.Date;
6   import java.util.GregorianCalendar;
7   
8   /***
9    * Collection of Date Utility
10   *
11   * @author <a href=mailto:draghetto@users.sourceforge.net>Massimiliano Amato</a>
12   */
13  public final class DateUtil {
14      /***
15       * Private default constuctor to prevent class instantiation.
16       */
17      private DateUtil() {
18      }
19  
20      /***
21       * Returns the number of full days between two dates
22       *
23       * @param startDate Start date
24       * @param endDate End date
25       *
26       * @return number of days between start and end date
27       */
28      public static int getDiffDays(Date startDate, Date endDate) {
29          final Calendar start = new GregorianCalendar();
30  
31          start.setTime(startDate);
32  
33          final Calendar end = new GregorianCalendar();
34  
35          end.setTime(endDate);
36  
37          int i;
38  
39          for (i = 0; start.before(end); i++) {
40              start.add(Calendar.DAY_OF_MONTH, 1);
41          }
42  
43          return i;
44      }
45  
46      /***
47       * Check if the two dates are in the same day
48       *
49       * @param date1 Date 1
50       * @param date2 Date 2
51       *
52       * @return true, if both dates are in the same day, even at different time
53       */
54      public static boolean equalsAsDays(Date date1, Date date2) {
55          final Date d1 = resetDay(date1);
56          final Date d2 = resetDay(date2);
57  
58          return d1.equals(d2);
59      }
60  
61      /***
62       * Reset the Date to midnight time
63       *
64       * @param date Date to reset
65       *
66       * @return a new Date at the same day but time set to midnight
67       */
68      public static Date resetDay(Date date) {
69          final Calendar cal = new GregorianCalendar();
70  
71          cal.setTime(date);
72          resetDay(cal);
73  
74          return cal.getTime();
75      }
76  
77      /***
78       * Reset the Calendar to midnight time
79       *
80       * @param cal Calendar to reset
81       *
82       * @return a new Calendar at the same day but time set to midnight
83       */
84      static Calendar resetDay(Calendar cal) {
85          cal.set(Calendar.HOUR_OF_DAY, 0);
86          cal.set(Calendar.MINUTE, 0);
87          cal.set(Calendar.SECOND, 0);
88          cal.set(Calendar.MILLISECOND, 0);
89  
90          return cal;
91      }
92  }