KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > DateTime


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. 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 Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.misc;
66
67 import com.jcorporate.expresso.core.db.DBException;
68 import com.jcorporate.expresso.core.i18n.Messages;
69 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
70 import org.apache.log4j.Logger;
71
72 import java.lang.ref.SoftReference JavaDoc;
73 import java.text.DateFormat JavaDoc;
74 import java.text.SimpleDateFormat JavaDoc;
75 import java.util.Calendar JavaDoc;
76 import java.util.Date JavaDoc;
77 import java.util.GregorianCalendar JavaDoc;
78 import java.util.HashMap JavaDoc;
79 import java.util.Locale JavaDoc;
80 import java.util.Map JavaDoc;
81
82 /**
83  * prepare timestamps for database storage
84  *
85  * @author Michael Nash
86  * @author Michael Rimov
87  * @author Yves Henri Amaizo
88  * @author David Lloyd
89  */

90 public class DateTime {
91
92     private static final Logger log = Logger.getLogger(DateTime.class);
93
94     /**
95      * Constructor
96      */

97     public DateTime() {
98         super();
99     } /* DateTime() */
100
101     /**
102      * Return the current date as a formatted string
103      *
104      * @return String The current date
105      */

106     public static String JavaDoc getDateString() {
107         Calendar JavaDoc rightNow = Calendar.getInstance();
108
109         return ("" + (rightNow.get(Calendar.MONTH) + 1) + "/" +
110                 rightNow.get(Calendar.DAY_OF_MONTH) + "/" +
111                 rightNow.get(Calendar.YEAR)).trim();
112     } /* getDateString() */
113
114
115     /**
116      * Get a date/time field formatted for insertion into a database
117      * Value of the date/time is the current date and time
118      *
119      * @return String The formatted date time field
120      */

121     public static String JavaDoc getDateTimeForDB() throws com.jcorporate.expresso.core.db.DBException {
122         return getDateTimeForDB(new Date JavaDoc(), "default");
123     } /* getDateTimeForDB() */
124
125     /**
126      * Get a date/time field formatted for insertion into a database
127      * Value of the date/time is the current date and time
128      *
129      * @param dbContext the database context to which to format this for.
130      * @return String The formatted date time field
131      */

132     public static String JavaDoc getDateTimeForDB(String JavaDoc dbContext) throws DBException {
133         return getDateTimeForDB(new Date JavaDoc(), dbContext);
134     }
135
136     /**
137      * Get a date/time field formatted for insertion into a database
138      * Value of the date/time is the current date and time
139      *
140      * @param year integer year
141      * @param month integer month value
142      * @param day integer day value
143      * @param hour integer hour value
144      * @param min integer minutes value
145      * @param sec integer seconds value
146      * @param context the data context to format this date-time string for.
147      * @return String The formatted date time field
148      */

149     public static String JavaDoc getDateTimeForDB(int year, int month,
150                                           int day, int hour,
151                                           int min, int sec, String JavaDoc context) throws com.jcorporate.expresso.core.db.DBException {
152         Calendar JavaDoc cal = new GregorianCalendar JavaDoc(year, month, day, hour, min, sec);
153
154         return getDateTimeForDB(cal.getTime(), context);
155     } /* getDateTimeForDB(int, int, int, int, int, int) */
156
157     /**
158      * Get a date/time field formatted for insertion into a database
159      *
160      * @param date java.util.Date to format into a string for a database
161      * @param context the data context to format the string for.
162      * @return String The formatted date time field
163      */

164     public static String JavaDoc getDateTimeForDB(Date JavaDoc date, String JavaDoc context) throws com.jcorporate.expresso.core.db.DBException {
165         if (date == null) {
166             return null;
167         }
168
169         String JavaDoc convertFormat = null;
170
171         // Format the current time. SimpleDateFormat formatter
172
try {
173             ConfigJdbc myConfig = ConfigManager.getJdbcRequired(context);
174
175             convertFormat = StringUtil.notNull(myConfig.getDateTimeSelectFormat());
176         } catch (ConfigurationException ce) {
177             throw new com.jcorporate.expresso.core.db.DBException(ce);
178         }
179
180         /* If no format was specified, don't change the existing field */
181         SimpleDateFormat JavaDoc formatter = null;
182         if (convertFormat.equals("")) {
183             // Format the current time. SimpleDateFormat formatter
184
formatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss ");
185         } else {
186             formatter = new SimpleDateFormat JavaDoc(convertFormat);
187         }
188
189         return formatter.format(date).trim();
190
191     } /* getDateTimeForDB(Date) */
192
193     /**
194      * Get a date/time field formatted for insertion into a database
195      * Value of the date/time is the current date and time
196      *
197      * @param year integer year
198      * @param month integer month value
199      * @param day integer day value
200      * @param hour integer hour value
201      * @param min integer minutes value
202      * @param sec integer seconds value
203      * @return String The formatted date time field
204      * @throws DBException upon error
205      */

206     public static String JavaDoc getDateTimeForDB(int year, int month,
207                                           int day, int hour,
208                                           int min, int sec) throws com.jcorporate.expresso.core.db.DBException {
209         Calendar JavaDoc cal = new GregorianCalendar JavaDoc(year, month, day, hour, min, sec);
210
211         return getDateTimeForDB(cal.getTime()).trim();
212     } /* getDateTimeForDB(int, int, int, int, int, int) */
213
214     /**
215      * Get a date/time field formatted for insertion into a database (default
216      * context)
217      *
218      * @param date the <code>java.util.Date</code> object to format for the
219      * database.
220      * @return String The formatted date time field
221      */

222     public static String JavaDoc getDateTimeForDB(Date JavaDoc date) throws com.jcorporate.expresso.core.db.DBException {
223         return getDateTimeForDB(date, "default");
224     } /* getDateTimeForDB(Date) */
225
226     /**
227      * Get a date/time string containing the current date and time,
228      * formatted for user readability
229      *
230      * @return String The formatted current date/time
231      */

232     public static String JavaDoc getDateTimeString() {
233
234         /* Calendar rightNow = Calendar.getInstance();
235 return ("" + (rightNow.get(Calendar.MONTH) + 1)+ "/"
236 + rightNow.get(Calendar.DAY_OF_MONTH)
237 + "/" + rightNow.get(Calendar.YEAR) + " "
238 + rightNow.get(Calendar.HOUR)
239 + ":" + rightNow.get(Calendar.MINUTE)
240 + ":" + rightNow.get(Calendar.SECOND)).trim(); */

241
242         // Format the current time. SimpleDateFormat formatter
243
SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc("E',' MMM d yyyy 'at' hh:mm:ss a");
244         Date JavaDoc currentTime_1 = new Date JavaDoc();
245         String JavaDoc dateString = formatter.format(currentTime_1);
246
247         return dateString.trim();
248     } /* getDateTimeString() */
249
250     /**
251      * Get a date/time string for a given date and time,
252      * formatted for user readability
253      *
254      * @param date <code>java.util.Date</code> to format for the default database
255      * @return String The formatted current date/time
256      */

257     public static String JavaDoc getDateTimeString(Date JavaDoc date) {
258         if (date == null) {
259             return null;
260         }
261         // Format the current time. SimpleDateFormat formatter
262
SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc("E',' MMM d yyyy 'at' hh:mm:ss a");
263         String JavaDoc dateString = formatter.format(date);
264
265         return dateString.trim();
266     } /* getDateTimeString() */
267
268     /**
269      * Get a time field formatted for insertion into a database
270      * Value of the time is the current time
271      *
272      * @return String The formatted time field
273      * @throws DBException upon error
274      */

275     public static String JavaDoc getTimeForDB() throws com.jcorporate.expresso.core.db.DBException {
276         return getTimeForDB(new Date JavaDoc(), "default");
277     } /* getTimeForDB() */
278
279     /**
280      * Get atime field formatted for insertion into a database
281      *
282      * @param hour hours as an int
283      * @param min minutes as an int
284      * @param sec seconds as an int
285      * @return String The formatted time field
286      */

287     public static String JavaDoc getTimeForDB(int hour, int min, int sec) throws com.jcorporate.expresso.core.db.DBException {
288         Calendar JavaDoc cal = new GregorianCalendar JavaDoc();
289         cal.set(Calendar.HOUR_OF_DAY, hour);
290         cal.set(Calendar.MINUTE, min);
291         cal.set(Calendar.SECOND, sec);
292
293         return getTimeForDB(cal.getTime(), "default");
294     } /* getTimeForDB(int, int, int) */
295
296     /**
297      * Get a time field formatted for insertion into a database
298      *
299      * @param date the <code>java.util.Date</code> object to format for
300      * the default database
301      * @return String The formatted time field
302      */

303     public static String JavaDoc getTimeForDB(Date JavaDoc date) throws com.jcorporate.expresso.core.db.DBException {
304         return getTimeForDB(date, "default");
305     } /* getTimeForDB(Date) */
306
307     /**
308      * Takes into account for the database context.
309      *
310      * @param date the <code>java.util.Date</code> object to format for
311      * @param context the data context to get the formatted string for.
312      * @return java.lang.String formatted for the specified context
313      */

314     public static String JavaDoc getTimeForDB(Date JavaDoc date, String JavaDoc context) throws com.jcorporate.expresso.core.db.DBException {
315         if (date == null) {
316             return null;
317         }
318
319         StringUtil.assertNotBlank(context,
320                 "DateTime.getTimeForDB(): parameter 'context' may not be mull");
321
322         String JavaDoc convertFormat = null;
323
324         // Format the current time. SimpleDateFormat formatter
325
try {
326             ConfigJdbc myConfig = ConfigManager.getJdbcRequired(context);
327
328             convertFormat = StringUtil.notNull(myConfig.getTimeSelectFormat());
329         } catch (ConfigurationException ce) {
330             throw new com.jcorporate.expresso.core.db.DBException(ce);
331         }
332
333         /* If no format was specified, don't change the existing field */
334         SimpleDateFormat JavaDoc formatter = null;
335         if (convertFormat.equals("")) {
336             // Format the current time. SimpleDateFormat formatter
337
formatter = new SimpleDateFormat JavaDoc("HH:mm:ss");
338         } else {
339             formatter = new SimpleDateFormat JavaDoc(convertFormat);
340         }
341
342         return formatter.format(date).trim();
343     }
344
345     /**
346      * Get a date field formatted for insertion into a database
347      * Value of the date is the current date
348      * author Yves Henri AMAIZO
349      *
350      * @return String The formatted date field
351      */

352     public static String JavaDoc getDateForDB() throws com.jcorporate.expresso.core.db.DBException {
353         return getDateForDB(new Date JavaDoc(), "default");
354     } /* getTimeForDB() */
355
356     /**
357      * Get a date field formatted for insertion into a database
358      * author Yves Henri AMAIZO
359      *
360      * @param year The year as an integer. ex: 1999
361      * @param mon The month as an integer [0-11]
362      * @param day of month The day of the month [1-31 variable]
363      * @return String The formatted date field
364      */

365     public static String JavaDoc getDateForDB(int year, int mon, int day) throws com.jcorporate.expresso.core.db.DBException {
366         Calendar JavaDoc cal = new GregorianCalendar JavaDoc();
367         cal.set(Calendar.YEAR, year);
368         cal.set(Calendar.MONTH, mon);
369         cal.set(Calendar.DAY_OF_MONTH, day);
370
371         return getDateForDB(cal.getTime(), "default");
372     } /* getTimeForDB(int, int, int) */
373
374     /**
375      * Get a time field formatted for insertion into a database
376      * author Yves Henri AMAIZO
377      *
378      * @param date The java.util.Date to format
379      * @return String The formatted date field
380      */

381     public static String JavaDoc getDateForDB(Date JavaDoc date) throws com.jcorporate.expresso.core.db.DBException {
382         return getDateForDB(date, "default");
383     } /* getTimeForDB(Date) */
384
385     /**
386      * Takes into account for the database context.
387      * author Yves Henri AMAIZO
388      *
389      * @param date The java.util.Date to format
390      * @param context The data context to format for
391      * @return String formatted for the specified database
392      */

393     public static String JavaDoc getDateForDB(Date JavaDoc date, String JavaDoc context) throws DBException {
394
395         if (date == null) {
396             return null;
397         }
398
399         StringUtil.assertNotBlank(context, "DateTime.getDateForDB(): parameter context may not be mull");
400
401         String JavaDoc convertFormat = null;
402
403         // Format the current time. SimpleDateFormat formatter
404
try {
405             ConfigJdbc myConfig = ConfigManager.getJdbcRequired(context);
406
407             convertFormat = StringUtil.notNull(myConfig.getDateSelectFormat());
408         } catch (ConfigurationException ce) {
409             throw new com.jcorporate.expresso.core.db.DBException(ce);
410         }
411
412         /* If no format was specified, don't change the existing field */
413         SimpleDateFormat JavaDoc formatter = null;
414         if (convertFormat.equals("")) {
415             // Format the current time. SimpleDateFormat formatter
416
formatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd");
417         } else {
418             formatter = new SimpleDateFormat JavaDoc(convertFormat);
419         }
420
421         return formatter.format(date).trim();
422     }
423
424
425     /**
426      * map of locale to date format strings for getDateFormatStrings()
427      */

428     transient private static SoftReference JavaDoc sDateFormatStrings = new SoftReference JavaDoc(new HashMap JavaDoc());
429
430     /**
431      * Get the Date or DateTime format for a Locale. For each of the date format characters (M,d,y,h,H,k,K,m,s),
432      * a lookup is made in the message bundle for the data format wanted.
433      * <br>
434      * For example, if DateFormat.getDateInstance(DateFormat.SHORT,locale) returns "M/dd/yy" and you wanted to show
435      * "mm/dd/yyyy" to the user, the resource bundle com.jcorporate.expresso.core.MessageBundle would need
436      * <br><pre>
437      * datetime.format.MM = mm
438      * datetime.format.dd = dd
439      * datetime.format.yy = yyyy
440      * </pre><br>
441      * <p/>
442      * The entries are cached because the DateFormat calls are VERY expensive.
443      * author David Lloyd
444      *
445      * @param dateOnly True if this is to get a date only format (m/d/yy) versus DateTime (m/d/yy h:m:s)
446      * @param locale The locale to get the format for. This may not be null
447      * @return String formatted for the date
448      */

449     public static String JavaDoc getDateFormatString(boolean dateOnly, Locale JavaDoc locale) {
450         DateTime.DateFormatCacheItem item = null;
451         String JavaDoc pattern = "";
452         String JavaDoc datePattern = "";
453         String JavaDoc dateTimePattern = "";
454
455         synchronized (sDateFormatStrings) {
456             Map JavaDoc dateFormatStrings = (Map JavaDoc) sDateFormatStrings.get();
457             if (dateFormatStrings == null) {
458                 dateFormatStrings = new HashMap JavaDoc();
459                 sDateFormatStrings = new SoftReference JavaDoc(dateFormatStrings);
460             }
461
462             item = (DateTime.DateFormatCacheItem) dateFormatStrings.get(DateFormatCacheItem.deriveKey(locale));
463
464             if (item == null) {
465                 DateFormat JavaDoc dateFormat;
466                 DateFormat JavaDoc dateTimeFormat;
467                 dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
468                 dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
469
470                 if (dateFormat instanceof SimpleDateFormat JavaDoc) {
471                     SimpleDateFormat JavaDoc simpleDateFormat = (SimpleDateFormat JavaDoc) dateFormat;
472                     datePattern = convertDateFormatStringToLocalized(locale, simpleDateFormat.toPattern());
473                 }
474                 if (dateTimeFormat instanceof SimpleDateFormat JavaDoc) {
475                     SimpleDateFormat JavaDoc simpleDateFormat = (SimpleDateFormat JavaDoc) dateTimeFormat;
476                     dateTimePattern = convertDateFormatStringToLocalized(locale, simpleDateFormat.toPattern());
477                 }
478
479                 item = new DateFormatCacheItem(locale, datePattern, dateTimePattern);
480                 dateFormatStrings.put(item.key, item);
481             } else {
482                 datePattern = item.dateFormat;
483                 dateTimePattern = item.dateTimeFormat;
484                 //System.err.println("DateTime.getDateFormatString cache hit");
485
}
486         }
487
488         if (dateOnly) {
489             pattern = datePattern;
490         } else {
491             pattern = dateTimePattern;
492         }
493
494         return pattern;
495     }
496
497     /**
498      * Get the Date or DateTime format for a Locale. Called when the item is not cached.
499      * author David Lloyd
500      *
501      * @param locale The locale to get the format for. This may not be null
502      * @param p The format string to localize
503      * @return String formatted for the date
504      */

505     private static String JavaDoc convertDateFormatStringToLocalized(Locale JavaDoc locale, String JavaDoc p) {
506         try {
507             FastStringBuffer fsb = new FastStringBuffer(16);
508             int n = p.length();
509             for (int i = 0; i < n; i++) {
510                 char c = p.charAt(i);
511                 switch (c) {
512                     case 'M':
513                     case 'd':
514                     case 'y':
515                     case 'h':
516                     case 'H':
517                     case 'k':
518                     case 'K':
519                     case 'm':
520                     case 's':
521                         {
522                             String JavaDoc s;
523                             try {
524                                 s = Messages.getString(locale, "datetime.format." + c + c);
525                                 fsb.append(s);
526                             } catch (Exception JavaDoc e) {
527                                 fsb.append(c).append(c);
528                             }
529                             while (i < n - 1 && c == p.charAt(i + 1)) {
530                                 i++;
531                             }
532                         }
533                         break;
534                     default:
535                         fsb.append(c);
536                         break;
537                 }
538             }
539             return fsb.toString();
540         } catch (Exception JavaDoc e) {
541             log.warn("Exception parsing date format string to localized string", e);
542         }
543         return "";
544     }
545
546     /**
547      * DateFormat items in sDateFormatStrings hash table.
548      * author David Lloyd
549      */

550     static class DateFormatCacheItem {
551         public String JavaDoc key;
552         public String JavaDoc dateFormat;
553         public String JavaDoc dateTimeFormat;
554
555         DateFormatCacheItem(Locale JavaDoc locale, String JavaDoc dateFormat, String JavaDoc dateTimeFormat) {
556             key = deriveKey(locale);
557             this.dateFormat = dateFormat;
558             this.dateTimeFormat = dateTimeFormat;
559         }
560
561         public String JavaDoc getKey() {
562             return key;
563         }
564
565         static String JavaDoc deriveKey(Locale JavaDoc locale) {
566             return locale.getCountry() + "-" + locale.getLanguage();
567         }
568     }
569
570 } /* DateTime */
571
Popular Tags