KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > DateUtils


1 /* ====================================================================
2  * The LateralNZ Software License, Version 1.0
3  *
4  * Copyright (c) 2003 LateralNZ. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by
21  * LateralNZ (http://www.lateralnz.org/) and other third parties."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "LateralNZ" must not be used to endorse or promote
26  * products derived from this software without prior written
27  * permission. For written permission, please
28  * contact oss@lateralnz.org.
29  *
30  * 5. Products derived from this software may not be called "Panther",
31  * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
32  * "LATERALNZ" appear in their name, without prior written
33  * permission of LateralNZ.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of LateralNZ. For more
51  * information on Lateral, please see http://www.lateralnz.com/ or
52  * http://www.lateralnz.org
53  *
54  */

55 package org.lateralnz.common.util;
56
57 import java.util.ArrayList JavaDoc;
58 import java.util.Calendar JavaDoc;
59 import java.util.Date JavaDoc;
60 import java.util.HashMap JavaDoc;
61 import java.util.List JavaDoc;
62 import java.util.Locale JavaDoc;
63 import java.text.ParseException JavaDoc;
64 import java.text.SimpleDateFormat JavaDoc;
65
66 /**
67  * date formatting utilities
68  *
69  * @author J R Briggs
70  */

71 public final class DateUtils implements Constants {
72   private static final String JavaDoc CLASSNAME = DateUtils.class.getName();
73
74  /**
75   * a constant representing "Mon"
76   */

77   public static final String JavaDoc MON = "Mon";
78   
79  /**
80   * a constant representing "Tues"
81   */

82   public static final String JavaDoc TUES = "Tues";
83
84  /**
85   * a constant representing "Wed"
86   */

87   public static final String JavaDoc WED = "Wed";
88
89   /**
90   * a constant representing "Thurs"
91   */

92   public static final String JavaDoc THURS = "Thurs";
93   
94  /**
95   * a constant representing "Fri"
96   */

97   public static final String JavaDoc FRI = "Fri";
98   
99  /**
100   * a constant representing "Sat"
101   */

102   public static final String JavaDoc SAT = "Sat";
103   
104  /**
105   * a constant representing "Sun"
106   */

107   public static final String JavaDoc SUN = "Sun";
108
109  /**
110   * a constant format string for the day
111   */

112   public static final String JavaDoc DAY_DATE_FORMAT = "dd";
113   
114  /**
115   * a constant format string for the month
116   */

117   public static final String JavaDoc MONTH_DATE_FORMAT = "MM";
118   
119  /**
120   * a constant format string for the year
121   */

122   public static final String JavaDoc YEAR_DATE_FORMAT = "yyyy";
123   
124  /**
125   * a constant format string for the reverse data (yyyyMMdd)
126   */

127   public static final String JavaDoc REVERSE_DATE_FORMAT = "yyyyMMdd";
128   
129  /**
130   * a constant format string for the date and tim (yyyyMMddhhmmss)
131   */

132   public static final String JavaDoc REVERSE_DATE_TIME_FORMAT = REVERSE_DATE_FORMAT + "HHmmss";
133
134  /**
135   * a constant for the number of milliseconds in a day
136   */

137   public static final long ONE_DAY_IN_MILLISECONDS = 1000*60*60*24;
138   
139   private static HashMap JavaDoc dateFormats = new HashMap JavaDoc();
140
141  /**
142   * a constant representing the beginning of time (or 01/01/0001)
143   */

144   public static Date JavaDoc BEGINNING_OF_TIME;
145   
146  /**
147   * a constant representing the end of time (or 31/12/9999)
148   */

149   public static Date JavaDoc END_OF_TIME;
150   
151   static {
152     try {
153       SimpleDateFormat JavaDoc tmp = new SimpleDateFormat JavaDoc(REVERSE_DATE_FORMAT);
154       BEGINNING_OF_TIME = tmp.parse("00010101");
155       END_OF_TIME = tmp.parse("99991231");
156     }
157     catch (Exception JavaDoc e) {
158       e.printStackTrace();
159     }
160   }
161
162   
163   private DateUtils() { }
164
165  /**
166   * add a value to a particular field (ie. day, month, year) of a date. Note: if you
167   * want to subtract, then add -1, -2, etc
168   * @param date the date object to add to
169   * @param field the field of the date (see Calendar for fields)
170   * @param amount the amount to add (or subtract if a negative number)
171   * @return a new date object
172   */

173   public static final Date JavaDoc add(Date JavaDoc date, int field, int amount) {
174     Calendar JavaDoc c = Calendar.getInstance();
175
176     c.setTime(date);
177
178     c.add(field, amount);
179
180     return c.getTime();
181   }
182
183  /**
184   * add a number of days to a date (basically a wrapper call to "add")
185   */

186   public static final Date JavaDoc addDays(Date JavaDoc date, int days) {
187     return add(date, Calendar.DATE, days);
188   }
189
190  /**
191   * apply a string time value to a date object
192   * @param d the date object to apply time to
193   * @param time the time to apply as one of "hh", "hhmm" or "hhmmss"
194   */

195   public static final Date JavaDoc applyTime(Date JavaDoc d, String JavaDoc time) {
196     if (time.length() < 6) {
197       time = StringUtils.rpad(time, '0', 6);
198     }
199     Calendar JavaDoc c = Calendar.getInstance();
200
201     c.setTime(d);
202     
203     c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.substring(0,2)));
204     c.set(Calendar.MINUTE, Integer.parseInt(time.substring(2,4)));
205     c.set(Calendar.SECOND, Integer.parseInt(time.substring(4,6)));
206     return c.getTime();
207   }
208   
209  /**
210   * Get a string representation of the month+year of current date.
211   * For instance, if it's "15/07/2003", this method returns "072003".
212   */

213   public static final String JavaDoc getCurrentMonthAsString() {
214     Calendar JavaDoc clen = Calendar.getInstance();
215     int month = clen.get(Calendar.MONTH);
216     int year = clen.get(Calendar.YEAR);
217
218     String JavaDoc m = EMPTY;
219     String JavaDoc y = EMPTY + year;
220     
221     if (month < 10) {
222       m += "0" + month;
223     }
224     else {
225       m += month;
226     }
227
228     return m+y;
229   }
230   
231  /**
232   * get a list of date objects starting from 'start' and finishing -before- 'end'.
233   * Note: start must be after end
234   * @param start the date to start with
235   * @param end the date to end with
236   */

237   public static final List JavaDoc getDateRangeList(Date JavaDoc start, Date JavaDoc end) {
238     ArrayList JavaDoc rtn = new ArrayList JavaDoc();
239     Calendar JavaDoc c = Calendar.getInstance();
240     c.setTime(start);
241     while (c.getTime().before(end)) {
242       rtn.add(c.getTime());
243       c.add(Calendar.DATE, 1);
244     }
245
246     return rtn;
247   }
248   
249   public static final int getDaysBetween(Date JavaDoc d1, Date JavaDoc d2) {
250     return (int)Math.abs((d1.getTime() - d2.getTime()) / 86400000);
251
252   }
253
254  /**
255   * get a string representation of a day of week (eg. "Mon", "Tues", etc)
256   * @return a string representation of the day
257   */

258   public static final String JavaDoc getShortDay(int dayOfWeek) {
259     switch (dayOfWeek) {
260       case Calendar.MONDAY :
261         return MON;
262       case Calendar.TUESDAY :
263         return TUES;
264       case Calendar.WEDNESDAY :
265         return WED;
266       case Calendar.THURSDAY :
267         return THURS;
268       case Calendar.FRIDAY :
269         return FRI;
270       case Calendar.SATURDAY :
271         return SAT;
272       case Calendar.SUNDAY :
273         return SUN;
274       default :
275         return EMPTY;
276     }
277   }
278
279  /**
280   * get a string representation of the day of the week the specified date represents
281   * @param date the date object to use
282   */

283   public static final String JavaDoc getShortDay(Date JavaDoc date) {
284     Calendar JavaDoc c = Calendar.getInstance();
285     c.setTime(date);
286     int day = c.get(Calendar.DAY_OF_WEEK);
287     return getShortDay(day);
288   }
289
290  /**
291   * get the first day of the week based upon the specified date (looks backwards from the
292   * date specified until it finds the monday)
293   * @returns a date object for the first day of the week
294   */

295   public static final Date JavaDoc getStartOfWeek(Date JavaDoc d) {
296     Calendar JavaDoc c = Calendar.getInstance();
297     c.setTime(d);
298     while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
299       c.add(Calendar.DATE, -1);
300     }
301     return c.getTime();
302   }
303
304  /**
305   * loads and caches a simpledateformat object
306   */

307   private static final SimpleDateFormat JavaDoc getFormat(String JavaDoc className, String JavaDoc pattern, Locale JavaDoc locale) {
308     SimpleDateFormat JavaDoc format;
309     String JavaDoc key = className + UNDERSCORE + pattern + UNDERSCORE + (locale != null ? locale.toString() : EMPTY);
310     if (!dateFormats.containsKey(key)) {
311       if (locale != null) {
312         format = new SimpleDateFormat JavaDoc(pattern, locale);
313       }
314       else {
315         format = new SimpleDateFormat JavaDoc(pattern);
316       }
317
318       synchronized (dateFormats) {
319         if (!dateFormats.containsKey(key)) {
320           dateFormats.put(key, format);
321         }
322       }
323     }
324     else {
325       format = (SimpleDateFormat JavaDoc)dateFormats.get(key);
326     }
327
328     return format;
329   }
330
331  /**
332   * converts a date object into a string representation using a cached simpledateformat
333   * @param callerClassName the class of the object calling this method (used for caching)
334   * @param d the date to convert
335   * @param pattern the date format to use
336   */

337   public static final String JavaDoc formatDate(String JavaDoc callerClassName, Date JavaDoc d, String JavaDoc pattern) {
338     return formatDate(callerClassName, d, null, pattern);
339   }
340
341  /**
342   * converts a date object into a string representation using a cached simpledateformat
343   * @param callerClassName the class of the object calling this method (used for caching)
344   * @param d the date to convert
345   * @param locale the locale to use in conversion
346   * @param pattern the date format to use
347   */

348   public static final String JavaDoc formatDate(String JavaDoc callerClassName, Date JavaDoc d, Locale JavaDoc locale, String JavaDoc pattern) {
349     if (d == null) {
350       return EMPTY;
351     }
352
353     SimpleDateFormat JavaDoc format = getFormat(callerClassName, pattern, locale);
354     synchronized (format) {
355       return format.format(d);
356     }
357   }
358
359  /**
360   * turns a string representation of a date into a date object using a cached format
361   * @param callerClassName the class of the object calling this method (used for caching)
362   * @param s the string date to convert
363   * @param pattern the date format to use
364   */

365   public static final Date JavaDoc parseDate(String JavaDoc callerClassName, String JavaDoc s, String JavaDoc pattern) throws ParseException JavaDoc {
366     return parseDate(callerClassName, s, null, pattern);
367   }
368
369  /**
370   * turns a string representation of a date into a date object using a cached format
371   * @param callerClassName the class of the object calling this method (used for caching)
372   * @param s the string date to convert
373   * @param locale the locale to use in conversion
374   * @param pattern the date format to use
375   */

376   public static final Date JavaDoc parseDate(String JavaDoc callerClassName, String JavaDoc s, Locale JavaDoc locale, String JavaDoc pattern) throws ParseException JavaDoc {
377     if (StringUtils.isEmpty(s)) {
378       return null;
379     }
380
381     SimpleDateFormat JavaDoc format = getFormat(callerClassName, pattern, locale);
382     synchronized (format) {
383       return format.parse(s);
384     }
385   }
386
387  /**
388   * returns true if two dates are equal using a particular date pattern
389   * @param callerClassName the class of the object calling this method (used for caching)
390   * @param d1 the first date
391   * @param d2 the second date
392   * @param pattern the date format to compare the two date objects by
393   */

394   public static final boolean isEqualUsingPattern(String JavaDoc callerClassName, Date JavaDoc d1, Date JavaDoc d2, String JavaDoc pattern) throws ParseException JavaDoc {
395     return isEqualUsingPattern(callerClassName, d1, d2, null, pattern);
396   }
397
398  /**
399   * returns true if two dates are equal using a particular date pattern
400   * @param callerClassName the class of the object calling this method (used for caching)
401   * @param d1 the first date
402   * @param d2 the second date
403   * @param locale the locale to use when comparing the dates
404   * @param pattern the date format to compare the two date objects by
405   */

406   public static final boolean isEqualUsingPattern(String JavaDoc callerClassName, Date JavaDoc d1, Date JavaDoc d2, Locale JavaDoc locale, String JavaDoc pattern) throws ParseException JavaDoc {
407     if (d1 == null || d2 == null) {
408       return false;
409     }
410
411     String JavaDoc s1 = formatDate(callerClassName, d1, locale, pattern);
412     String JavaDoc s2 = formatDate(callerClassName, d2, locale, pattern);
413
414     Date JavaDoc dn1 = parseDate(callerClassName, s1, locale, pattern);
415     Date JavaDoc dn2 = parseDate(callerClassName, s2, locale, pattern);
416
417     return dn1.equals(dn2);
418   }
419
420  /**
421   * takes a date object and sets a time value against it
422   * @param callerClassName the class of the object calling this method (used for caching)
423   * @param d the date object to use
424   * @param time the string representation of the time to set on the date object
425   * @param timeformat the format of the time
426   * @returns a new date object with the time set
427   */

428   public static final Date JavaDoc setTime(String JavaDoc callerClassName, Date JavaDoc d, String JavaDoc time, String JavaDoc timeformat) throws ParseException JavaDoc {
429     String JavaDoc s = formatDate(callerClassName, d, REVERSE_DATE_FORMAT) + time;
430     return parseDate(callerClassName, s, REVERSE_DATE_FORMAT + timeformat);
431   }
432   
433 }
Popular Tags