KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > util > DateUtil


1 /*
2  * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/DateUtil.java,v 1.36 2006/04/15 02:59:20 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.36 $
5  * $Date: 2006/04/15 02:59:20 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding MyVietnam and MyVietnam CoreLib
12  * MUST remain intact in the scripts and source code.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  *
28  * Correspondence and Marketing Questions can be sent to:
29  * info at MyVietnam net
30  *
31  * @author: Minh Nguyen
32  * @author: Mai Nguyen
33  */

34 package net.myvietnam.mvncore.util;
35
36 import java.sql.Timestamp JavaDoc;
37 import java.text.DateFormat JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.util.*;
40 import java.util.Date JavaDoc;
41
42 import net.myvietnam.mvncore.MVNCoreConfig;
43
44 /**
45  * @todo: add config option to this class
46  */

47 public final class DateUtil {
48
49     public static final long SECOND = 1000;
50     public static final long MINUTE = SECOND * 60;
51     public static final long HOUR = MINUTE * 60;
52     public static final long DAY = HOUR * 24;
53     public static final long WEEK = DAY * 7;
54     public static final long YEAR = DAY * 365; // or 366 ???
55

56     /**
57      * This is the time difference between GMT time and Vietnamese time
58      */

59     public static final long GMT_VIETNAM_TIME_OFFSET = HOUR * 7;
60
61     /**
62      * RFC 822 date format, for RSS 2.0
63      * Sat, 07 Sep 2002 00:00:01 GMT
64      */

65     public static final String JavaDoc RFC_822_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss Z";
66
67     /**
68      * ISO 8601 [W3CDTF] date format
69      * 2005-06-05T14:52:57EDT
70      * Note: not sure Z or z is correct
71      */

72     public static final String JavaDoc ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
73
74     /**
75      * UTC style date format
76      */

77     public static final String JavaDoc UTC_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
78
79     /**
80      * This is the time difference between GMT time and SERVER time
81      */

82     //private static long SERVER_TIME_OFFSET = HOUR * (new DateOptions()).serverHourOffset;
83

84     private static DateFormat JavaDoc ddMMyyyyFormat = new SimpleDateFormat JavaDoc("dd/MM/yyyy");
85     private static DateFormat JavaDoc yyyyMMddFormat = new SimpleDateFormat JavaDoc("yyyy-MM-dd");
86     private static DateFormat JavaDoc rfc822Format = new SimpleDateFormat JavaDoc(RFC_822_DATE_FORMAT, Locale.US);
87     private static DateFormat JavaDoc iso8601Format = new SimpleDateFormat JavaDoc(ISO_8601_DATE_FORMAT, Locale.US);
88     private static DateFormat JavaDoc dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT);
89     private static DateFormat JavaDoc datetimeFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);
90     private static DateFormat JavaDoc viDateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, new Locale("vi", "VN"));
91     private static DateFormat JavaDoc viDatetimeFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, new Locale("vi", "VN"));
92     private static DateFormat JavaDoc headerTimeFormat = new SimpleDateFormat JavaDoc("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
93     //private static DateFormat utcFormat = new SimpleDateFormat(UTC_DATE_FORMAT);
94

95     static {
96         TimeZone gmt = TimeZone.getTimeZone("GMT");
97         headerTimeFormat.setTimeZone(gmt);
98     }
99
100     /**
101      * private constructor
102      */

103     private DateUtil() {// prevent instantiation
104
}
105
106     public static synchronized String JavaDoc getDateDDMMYYYY(Date JavaDoc date) {
107         return ddMMyyyyFormat.format(date);
108     }
109
110     public static synchronized String JavaDoc getDateYYYYMMDD(Date JavaDoc date) {
111         return yyyyMMddFormat.format(date);
112     }
113
114     public static synchronized String JavaDoc getDateRFC822(Date JavaDoc date) {
115         return rfc822Format.format(date);
116     }
117
118     public static synchronized String JavaDoc getDateISO8601(Date JavaDoc date) {
119         String JavaDoc formattedDate = iso8601Format.format(date);
120         int length = formattedDate.length();
121         if (length > 2) {
122             return new StringBuffer JavaDoc(64).append(formattedDate.substring(0, length - 2)).append(":").append(formattedDate.substring(length - 2)).toString();
123         }
124         return formattedDate;
125     }
126
127     public static synchronized String JavaDoc getHTTPHeaderTime(Date JavaDoc date) {
128         return headerTimeFormat.format(date);
129     }
130
131     public static synchronized String JavaDoc formatDate(Date JavaDoc date) {
132         return dateFormat.format(date);
133     }
134
135     public static synchronized String JavaDoc formatDateTime(Date JavaDoc date) {
136         return datetimeFormat.format(date);
137     }
138
139     public static synchronized String JavaDoc formatViDate(Date JavaDoc date) {
140         return viDateFormat.format(date);
141     }
142
143     public static synchronized String JavaDoc formatViDateTime(Date JavaDoc date) {
144         return viDatetimeFormat.format(date);
145     }
146
147     public static String JavaDoc getViDateTimeDesc() {
148         return formatViDateTime(getVietnamDateFromGMTDate(getCurrentGMTTimestamp()));
149     }
150
151     public static String JavaDoc getViDateDesc() {
152         return formatViDate(getVietnamDateFromGMTDate(getCurrentGMTTimestamp()));
153     }
154
155     public static Timestamp JavaDoc getCurrentGMTTimestamp() {
156         return new Timestamp JavaDoc(System.currentTimeMillis() - (HOUR * MVNCoreConfig.getServerHourOffset()));
157     }
158
159     public static void updateCurrentGMTTimestamp(Timestamp JavaDoc timeToUpdate) {
160         timeToUpdate.setTime(System.currentTimeMillis() - (HOUR * MVNCoreConfig.getServerHourOffset()));
161     }
162
163     public static Date JavaDoc getVietnamDateFromGMTDate(Date JavaDoc date) {
164         return new Date JavaDoc(date.getTime() + GMT_VIETNAM_TIME_OFFSET);
165     }
166
167     /* Note that Timestamp is extended from Date
168     public static Date getVietnamTimestampFromGMTTimestamp(Timestamp date) {
169         return new Timestamp(date.getTime() + GMT_VIETNAM_TIME_OFFSET);
170     }*/

171
172     public static Date JavaDoc convertGMTDate(Date JavaDoc gmtDate, double hourOffset) {
173         return new Date JavaDoc(gmtDate.getTime() + (long)(hourOffset*HOUR));
174     }
175
176     public static Timestamp JavaDoc convertGMTTimestamp(Timestamp JavaDoc gmtTimestamp, double hourOffset) {
177         return new Timestamp JavaDoc(gmtTimestamp.getTime() + (long)(hourOffset*HOUR));
178     }
179
180     public static Timestamp JavaDoc getCurrentGMTTimestampExpiredYear(int offsetYear) {
181         //return new Timestamp(System.currentTimeMillis() + offsetYear*(365*24*60*60*1000));
182
Calendar now = Calendar.getInstance();
183         now.add(Calendar.YEAR, offsetYear);
184         return new Timestamp JavaDoc(now.getTime().getTime());
185     }
186
187     public static Timestamp JavaDoc getCurrentGMTTimestampExpiredMonth(int offsetMonth) {
188         Calendar now = Calendar.getInstance();
189         now.add(Calendar.MONTH, offsetMonth);
190         return new Timestamp JavaDoc(now.getTime().getTime());
191     }
192
193     public static Timestamp JavaDoc getCurrentGMTTimestampExpiredDay(int offsetDay) {
194         Calendar now = Calendar.getInstance();
195         now.add(Calendar.DATE,offsetDay);
196         return new Timestamp JavaDoc(now.getTime().getTime());
197     }
198
199     public static String JavaDoc format(Date JavaDoc date, String JavaDoc pattern) {
200         DateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc (pattern, Locale.US);
201         return formatter.format(date);
202     }
203
204     public static String JavaDoc formatDuration(long duration, String JavaDoc pattern) {
205         DurationFormater time = new DurationFormater(duration, pattern);
206         return time.toString();
207     }
208
209     public static String JavaDoc formatDuration(long duration) {
210         DurationFormater time = new DurationFormater(duration, null);
211         return time.toString();
212     }
213
214     public static void main (String JavaDoc[] agrs) {
215         long duration = (long)1000 * 60 * 60 *24 * 130 + (long)1000 * 60 * 80;
216         System.out.println(duration);
217         System.out.println("Duration of " + duration + " duration = " + formatDuration(duration));
218         Date JavaDoc d = new Date JavaDoc();
219         System.out.println(" Date is " + DateUtil.getDateISO8601(d));
220     }
221 }
222
223 class DurationFormater {
224     public static final long MILISECONDS_PER_SECOND = 1000;
225     public static final long SECONDS_PER_MINUTE = 60;
226     public static final long MINUTES_PER_HOUR = 60;
227     public static final long HOURS_PER_DAY = 24;
228
229     public static final int MILISECOND = 0;
230     public static final int SECOND = 1;
231     public static final int MINUTE = 2;
232     public static final int HOUR = 3;
233     public static final int DAY = 4;
234
235
236     public static final String JavaDoc PATTERNS[] = {
237         "@ms", "@s", "@m", "@h", "@d"
238     };
239     private static final long[] AMOUNTS = {
240         MILISECONDS_PER_SECOND,
241         SECONDS_PER_MINUTE,
242         MINUTES_PER_HOUR,
243         HOURS_PER_DAY
244     };
245     private static long[] times = new long[5];
246     private long time;
247     private String JavaDoc pattern;
248     private boolean detail = false;
249
250     public DurationFormater() {
251     }
252
253     public DurationFormater(long time, String JavaDoc pattern) {
254         this.time = time;
255         this.pattern = pattern;
256         update();
257     }
258
259     public DurationFormater(long time) {
260         this.time = time;
261         update();
262     }
263
264     private void update() {
265         long remain = time;
266         for (int i = 0; i < AMOUNTS.length; i++) {
267             times[i] = remain % AMOUNTS[i];
268             remain = remain / AMOUNTS[i];
269         }
270         times[DAY] = (int) remain;
271     }
272
273     /* @h
274      * @M --> Month
275      * @m --> minute
276      * @ms --> milisecond
277      * @s --> second
278      */

279     public void setPattern(String JavaDoc pattern) {
280         this.pattern = pattern;
281     }
282
283     public long getTime() {
284         return time;
285     }
286
287     public void setTime(long duration) {
288         time = duration;
289         update();
290     }
291
292     public long getMiliseconds() {
293         return times[MILISECOND];
294     }
295
296     public long getSeconds() {
297         return times[SECOND];
298     }
299
300     public long getMinutes() {
301         return times[MINUTE];
302     }
303
304     public long getHours() {
305         return times[HOUR];
306     }
307
308     public long getDays() {
309         return times[DAY];
310     }
311
312     public void setDetail(boolean detail) {
313         this.detail = detail;
314     }
315
316     public String JavaDoc getString() {
317         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(1024);
318         buffer.append(pattern);
319         for (int i = 0; i < PATTERNS.length; i++) {
320             int start = -1;
321             int end = -1;
322             // Note, in JDK 1.3, StringBuffer does not have method indexOf
323
while ((start = buffer.toString().indexOf(PATTERNS[i])) > -1) {
324                 end = start + PATTERNS[i].length();
325                 buffer.replace(start, end, String.valueOf(times[i]));
326             }
327         }
328         return buffer.toString();
329     }
330
331     public String JavaDoc toString() {
332         if (pattern != null) {
333             return getString();
334         }
335
336         StringBuffer JavaDoc desc = new StringBuffer JavaDoc(256);
337         if (times[DAY] > 0) {
338             desc.append(checkPlural(times[DAY], "day"));
339         }
340         if (times[HOUR] > 0) {
341             desc.append(checkPlural(times[HOUR], "hour"));
342         }
343         if ((times[MINUTE] > 0) || (times[DAY] == 0 && times[MINUTE] == 0)) {
344             desc.append(checkPlural(times[MINUTE], "minute"));
345         }
346         if (detail) {
347             desc.append(checkPlural(times[SECOND], "second"));
348             desc.append(checkPlural(times[MILISECOND], "milisecond"));
349         }
350         return desc.toString();
351     }
352
353     private static String JavaDoc checkPlural(long amount, String JavaDoc unit) {
354         StringBuffer JavaDoc desc = new StringBuffer JavaDoc(20);
355        desc.append(amount).append(" ").append(unit);
356         if (amount > 1) {
357             desc.append("s");
358         }
359         return desc.append(" ").toString();
360     }
361 }
362
Popular Tags