01: /* DateFormats.java
02:
03: {{IS_NOTE
04:
05: Purpose:
06: Description:
07: History:
08: 91/01/17 15:22:22, Create, Tom M. Yeh.
09: }}IS_NOTE
10:
11: Copyright (C) 2001 Potix Corporation. All Rights Reserved.
12:
13: {{IS_RIGHT
14: This program is distributed under GPL Version 2.0 in the hope that
15: it will be useful, but WITHOUT ANY WARRANTY.
16: }}IS_RIGHT
17: */
18: package org.zkoss.text;
19:
20: import java.util.Locale;
21: import java.util.Date;
22: import java.text.DateFormat;
23: import java.text.SimpleDateFormat;
24: import java.text.ParseException;
25:
26: import org.zkoss.util.Locales;
27:
28: /**
29: * DateFormat relevant utilities.
30: *
31: * @author tomyeh
32: */
33: public class DateFormats {
34: /**
35: * Parses a string to a date.
36: * It is smart enough to know whether to use DateFormat.getDateInstance
37: * and DateFormat.getDateTimeInstance.
38: * It also uses {@link Locales#getCurrent}.
39: */
40: public static final Date parse(String s) throws ParseException {
41: final Locale locale = Locales.getCurrent();
42:
43: if (s.indexOf(':') < 0) { //date only
44: final DateFormat df = DateFormat.getDateInstance(
45: DateFormat.DEFAULT, locale);
46: return df.parse(s);
47: } else {
48: synchronized (TO_STRING_FORMAT) {
49: try {
50: return TO_STRING_FORMAT.parse(s);
51: } catch (ParseException ex) { //ignore it
52: }
53: }
54: final DateFormat df = DateFormat.getDateTimeInstance(
55: DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
56: return df.parse(s);
57: }
58: }
59:
60: /** The date formatter for generating Date.toString().
61: * To use it, remember to synchronized(TO_STRING_FORMAT)
62: */
63: private static final SimpleDateFormat TO_STRING_FORMAT = new SimpleDateFormat(
64: "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
65:
66: /** Formats a Date object based on the current Locale.
67: *
68: * @param dateOnly indicates whether to show only date; false to show
69: * both date and time
70: */
71: public static final String format(Date d, boolean dateOnly) {
72: Locale locale = Locales.getCurrent();
73:
74: if (dateOnly) {
75: DateFormat df = DateFormat.getDateInstance(
76: DateFormat.DEFAULT, locale);
77: return df.format(d);
78: } else {
79: DateFormat df = DateFormat.getDateTimeInstance(
80: DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
81: return df.format(d);
82: }
83: }
84: }
|