KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > util > DateUtil


1 package org.roller.util;
2
3 import java.text.ParseException JavaDoc;
4 import java.text.SimpleDateFormat JavaDoc;
5 import java.util.Calendar JavaDoc;
6 import java.util.Date JavaDoc;
7 import java.util.Locale JavaDoc;
8
9 /**
10  * General purpose date utilities.
11  * @author Mark Saarinen
12  * @author Lance Lavandowska
13  */

14 public abstract class DateUtil extends Object JavaDoc
15 {
16     public static final long millisInDay = 86400000;
17
18     // some static date formats
19
private static SimpleDateFormat JavaDoc[] mDateFormats = loadDateFormats();
20     
21     private static final SimpleDateFormat JavaDoc mFormat8chars =
22         new SimpleDateFormat JavaDoc("yyyyMMdd");
23
24     private static final SimpleDateFormat JavaDoc mFormatIso8601Day =
25         new SimpleDateFormat JavaDoc("yyyy-MM-dd");
26
27     private static final SimpleDateFormat JavaDoc mFormatIso8601 =
28         new SimpleDateFormat JavaDoc("yyyy-MM-dd'T'HH:mm:ssZ");
29     
30     // http://www.w3.org/Protocols/rfc822/Overview.html#z28
31
// Using Locale.US to fix ROL-725 and ROL-628
32
private static final SimpleDateFormat JavaDoc mFormatRfc822 =
33         new SimpleDateFormat JavaDoc("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
34
35     private static SimpleDateFormat JavaDoc[] loadDateFormats()
36     {
37         SimpleDateFormat JavaDoc[] temp = {
38             //new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS a"),
39
new SimpleDateFormat JavaDoc("EEE MMM d HH:mm:ss z yyyy"), // standard Date.toString() results
40
new SimpleDateFormat JavaDoc("M/d/yy hh:mm:ss"),
41             new SimpleDateFormat JavaDoc("M/d/yyyy hh:mm:ss"),
42             new SimpleDateFormat JavaDoc("M/d/yy hh:mm a"),
43             new SimpleDateFormat JavaDoc("M/d/yyyy hh:mm a"),
44             new SimpleDateFormat JavaDoc("M/d/yy HH:mm"),
45             new SimpleDateFormat JavaDoc("M/d/yyyy HH:mm"),
46             new SimpleDateFormat JavaDoc("dd.MM.yyyy HH:mm:ss"),
47             new SimpleDateFormat JavaDoc("yy-MM-dd HH:mm:ss.SSS"),
48             new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss.SSS"), // standard Timestamp.toString() results
49
new SimpleDateFormat JavaDoc("M-d-yy HH:mm"),
50             new SimpleDateFormat JavaDoc("M-d-yyyy HH:mm"),
51             new SimpleDateFormat JavaDoc("MM/dd/yyyy HH:mm:ss.SSS"),
52             new SimpleDateFormat JavaDoc("M/d/yy"),
53             new SimpleDateFormat JavaDoc("M/d/yyyy"),
54             new SimpleDateFormat JavaDoc("M-d-yy"),
55             new SimpleDateFormat JavaDoc("M-d-yyyy"),
56             new SimpleDateFormat JavaDoc("MMMM d, yyyyy"),
57             new SimpleDateFormat JavaDoc("MMM d, yyyyy")
58         };
59     
60         return temp;
61     }
62     //-----------------------------------------------------------------------
63
/**
64      * Gets the array of SimpleDateFormats that DateUtil knows about.
65     **/

66     private static SimpleDateFormat JavaDoc[] getFormats()
67     {
68         return mDateFormats;
69     }
70
71     //-----------------------------------------------------------------------
72
/**
73      * Returns a Date set to the last possible millisecond of the day, just
74      * before midnight. If a null day is passed in, a new Date is created.
75      * midnight (00m 00h 00s)
76      */

77     public static Date JavaDoc getEndOfDay(Date JavaDoc day)
78     {
79         return getEndOfDay(day,Calendar.getInstance());
80     }
81     public static Date JavaDoc getEndOfDay(Date JavaDoc day,Calendar JavaDoc cal)
82     {
83         if (day == null) day = new Date JavaDoc();
84         cal.setTime(day);
85         cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
86         cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE));
87         cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND));
88         cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
89         return cal.getTime();
90     }
91
92     //-----------------------------------------------------------------------
93
/**
94      * Returns a Date set to the first possible millisecond of the day, just
95      * after midnight. If a null day is passed in, a new Date is created.
96      * midnight (00m 00h 00s)
97      */

98     public static Date JavaDoc getStartOfDay(Date JavaDoc day)
99     {
100         return getStartOfDay(day, Calendar.getInstance());
101     }
102     /**
103      * Returns a Date set to the first possible millisecond of the day, just
104      * after midnight. If a null day is passed in, a new Date is created.
105      * midnight (00m 00h 00s)
106      */

107     public static Date JavaDoc getStartOfDay(Date JavaDoc day, Calendar JavaDoc cal)
108     {
109         if (day == null) day = new Date JavaDoc();
110         cal.setTime(day);
111         cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
112         cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
113         cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
114         cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
115         return cal.getTime();
116     }
117
118     /**
119      * Returns a Date set just to Noon, to the closest possible millisecond
120      * of the day. If a null day is passed in, a new Date is created.
121      * nnoon (00m 12h 00s)
122      */

123     public static Date JavaDoc getNoonOfDay(Date JavaDoc day, Calendar JavaDoc cal)
124     {
125         if (day == null) day = new Date JavaDoc();
126         cal.setTime(day);
127         cal.set(Calendar.HOUR_OF_DAY, 12);
128         cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
129         cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
130         cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
131         return cal.getTime();
132     }
133     
134     //-----------------------------------------------------------------------
135
public static Date JavaDoc parseFromFormats(String JavaDoc aValue)
136     {
137         if (StringUtils.isEmpty(aValue)) return null;
138
139         // get DateUtil's formats
140
SimpleDateFormat JavaDoc formats[] = DateUtil.getFormats();
141         if (formats == null) return null;
142
143         // iterate over the array and parse
144
Date JavaDoc myDate = null;
145         for (int i = 0; i <formats.length; i++)
146         {
147             try
148             {
149                 myDate = DateUtil.parse(aValue, formats[i]);
150                 //if (myDate instanceof Date)
151
return myDate;
152             }
153             catch (Exception JavaDoc e)
154             {
155                 // do nothing because we want to try the next
156
// format if current one fails
157
}
158        }
159        // haven't returned so couldn't parse
160
return null;
161     }
162
163     //-----------------------------------------------------------------------
164
public static java.sql.Timestamp JavaDoc parseTimestampFromFormats(String JavaDoc aValue)
165     {
166         if (StringUtils.isEmpty(aValue)) return null;
167
168         // call the regular Date formatter
169
Date JavaDoc myDate = DateUtil.parseFromFormats(aValue);
170         if (myDate != null) return new java.sql.Timestamp JavaDoc(myDate.getTime());
171         return null;
172     }
173     //-----------------------------------------------------------------------
174
/**
175      * Returns a java.sql.Timestamp equal to the current time
176     **/

177     public static java.sql.Timestamp JavaDoc now()
178     {
179         return new java.sql.Timestamp JavaDoc(new java.util.Date JavaDoc().getTime());
180     }
181
182     //-----------------------------------------------------------------------
183
/**
184      * Returns a string the represents the passed-in date parsed
185      * according to the passed-in format. Returns an empty string
186      * if the date or the format is null.
187     **/

188     public static String JavaDoc format(Date JavaDoc aDate, SimpleDateFormat JavaDoc aFormat)
189     {
190         if (aDate == null || aFormat == null ) { return ""; }
191         synchronized (aFormat)
192         {
193             return aFormat.format(aDate);
194         }
195     }
196
197     //-----------------------------------------------------------------------
198
/**
199      * Tries to take the passed-in String and format it as a date string in the
200      * the passed-in format.
201     **/

202     public static String JavaDoc formatDateString(String JavaDoc aString, SimpleDateFormat JavaDoc aFormat)
203     {
204         if (StringUtils.isEmpty(aString) || aFormat == null) return "";
205         try
206         {
207             java.sql.Timestamp JavaDoc aDate = parseTimestampFromFormats(aString);
208             if (aDate != null)
209             {
210                 return DateUtil.format(aDate, aFormat);
211             }
212         }
213         catch (Exception JavaDoc e)
214         {
215             // Could not parse aString.
216
}
217         return "";
218     }
219
220     //-----------------------------------------------------------------------
221
/**
222      * Returns a Date using the passed-in string and format. Returns null if the string
223      * is null or empty or if the format is null. The string must match the format.
224     **/

225     public static Date JavaDoc parse(String JavaDoc aValue, SimpleDateFormat JavaDoc aFormat) throws ParseException JavaDoc
226     {
227         if (StringUtils.isEmpty(aValue) || aFormat == null)
228         {
229             return null;
230         }
231
232         return aFormat.parse(aValue);
233     }
234
235     //-----------------------------------------------------------------------
236
/**
237      * Returns true if endDate is after startDate or if startDate equals endDate
238      * or if they are the same date. Returns false if either value is null.
239     **/

240     public static boolean isValidDateRange(Date JavaDoc startDate, Date JavaDoc endDate)
241     {
242         return isValidDateRange(startDate, endDate, true);
243     }
244
245     //-----------------------------------------------------------------------
246
/**
247      * Returns true if endDate is after startDate or if startDate equals endDate.
248      * Returns false if either value is null. If equalOK, returns true if the
249      * dates are equal.
250     **/

251     public static boolean isValidDateRange(Date JavaDoc startDate, Date JavaDoc endDate, boolean equalOK)
252     {
253         // false if either value is null
254
if (startDate == null || endDate == null) { return false; }
255
256         if (equalOK)
257         {
258             // true if they are equal
259
if (startDate.equals(endDate)) { return true; }
260         }
261
262         // true if endDate after startDate
263
if (endDate.after(startDate)) { return true; }
264
265         return false;
266     }
267
268     //-----------------------------------------------------------------------
269
// returns full timestamp format
270
public static java.text.SimpleDateFormat JavaDoc defaultTimestampFormat()
271     {
272         return new java.text.SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss.SSS");
273     }
274
275     //-----------------------------------------------------------------------
276
// convenience method returns minimal date format
277
public static java.text.SimpleDateFormat JavaDoc get8charDateFormat()
278     {
279         return DateUtil.mFormat8chars;
280     }
281
282     //-----------------------------------------------------------------------
283
// convenience method returns minimal date format
284
public static java.text.SimpleDateFormat JavaDoc defaultDateFormat()
285     {
286         return DateUtil.friendlyDateFormat(true);
287     }
288
289     //-----------------------------------------------------------------------
290
// convenience method
291
public static String JavaDoc defaultTimestamp(Date JavaDoc date)
292     {
293         return DateUtil.format(date, DateUtil.defaultTimestampFormat());
294     }
295     
296     //-----------------------------------------------------------------------
297
// convenience method
298
public static String JavaDoc defaultDate(Date JavaDoc date)
299     {
300         return DateUtil.format(date, DateUtil.defaultDateFormat());
301     }
302
303     //-----------------------------------------------------------------------
304
// convenience method returns long friendly timestamp format
305
public static java.text.SimpleDateFormat JavaDoc friendlyTimestampFormat()
306     {
307         return new java.text.SimpleDateFormat JavaDoc("dd.MM.yyyy HH:mm:ss");
308     }
309
310     //-----------------------------------------------------------------------
311
// convenience method returns long friendly formatted timestamp
312
public static String JavaDoc friendlyTimestamp(Date JavaDoc date)
313     {
314         return DateUtil.format(date, DateUtil.friendlyTimestampFormat());
315     }
316
317     //-----------------------------------------------------------------------
318
// convenience method returns long friendly formatted timestamp
319
public static String JavaDoc format8chars(Date JavaDoc date)
320     {
321         return DateUtil.format(date, mFormat8chars);
322     }
323
324     //-----------------------------------------------------------------------
325
// convenience method returns long friendly formatted timestamp
326
public static String JavaDoc formatIso8601Day(Date JavaDoc date)
327     {
328         return DateUtil.format(date, mFormatIso8601Day);
329     }
330
331     //-----------------------------------------------------------------------
332
public static String JavaDoc formatRfc822(Date JavaDoc date)
333     {
334         return DateUtil.format(date,mFormatRfc822);
335     }
336
337     //-----------------------------------------------------------------------
338
// This is a hack, but it seems to work
339
public static String JavaDoc formatIso8601(Date JavaDoc date)
340     {
341         if (date == null) return "";
342         
343         // Add a colon 2 chars before the end of the string
344
// to make it a valid ISO-8601 date.
345

346         String JavaDoc str = DateUtil.format(date,mFormatIso8601);
347         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
348         sb.append( str.substring(0,str.length()-2) );
349         sb.append( ":" );
350         sb.append( str.substring(str.length()-2) );
351         return sb.toString();
352     }
353
354     //-----------------------------------------------------------------------
355
// convenience method returns minimal date format
356
public static java.text.SimpleDateFormat JavaDoc minimalDateFormat()
357     {
358         return DateUtil.friendlyDateFormat(true);
359     }
360
361     //-----------------------------------------------------------------------
362
// convenience method using minimal date format
363
public static String JavaDoc minimalDate(Date JavaDoc date)
364     {
365         return DateUtil.format(date, DateUtil.minimalDateFormat());
366     }
367
368     //-----------------------------------------------------------------------
369
// convenience method that returns friendly data format
370
// using full month, day, year digits.
371
public static java.text.SimpleDateFormat JavaDoc fullDateFormat()
372     {
373         return DateUtil.friendlyDateFormat(false);
374     }
375
376     //-----------------------------------------------------------------------
377
public static String JavaDoc fullDate(Date JavaDoc date)
378     {
379         return DateUtil.format(date, DateUtil.fullDateFormat());
380     }
381
382     //-----------------------------------------------------------------------
383
/** Returns a "friendly" date format.
384      * @param mimimalFormat Should the date format allow single digits.
385     **/

386     public static java.text.SimpleDateFormat JavaDoc friendlyDateFormat(boolean minimalFormat)
387     {
388         if (minimalFormat)
389         {
390             return new java.text.SimpleDateFormat JavaDoc("d.M.yy");
391         }
392
393         return new java.text.SimpleDateFormat JavaDoc("dd.MM.yyyy");
394     }
395
396     //-----------------------------------------------------------------------
397
/**
398      * Format the date using the "friendly" date format.
399      */

400     public static String JavaDoc friendlyDate(Date JavaDoc date, boolean minimalFormat)
401     {
402         return DateUtil.format(date, DateUtil.friendlyDateFormat(minimalFormat));
403     }
404
405     //-----------------------------------------------------------------------
406
// convenience method
407
public static String JavaDoc friendlyDate(Date JavaDoc date)
408     {
409         return DateUtil.format(date, DateUtil.friendlyDateFormat(true));
410     }
411     
412     public static Date JavaDoc parseIso8601(String JavaDoc value) throws Exception JavaDoc
413     {
414         return ISO8601DateParser.parse(value);
415     }
416 }
417
Popular Tags