01: package net.matuschek.http;
02:
03: import java.util.*;
04: import java.text.*;
05:
06: /**
07: * Common place for date utils.
08: * Copied and modified from org.apache.tomcat.util.buf
09: * @author <a href="mailto:d.stucky@insiders.de">Daniel Stucky</a>
10: * @version $Revision: 1.1 $
11: **/
12:
13: public class HTTPDateTool {
14: /** GMT timezone - all HTTP dates are on GMT
15: */
16: public final static TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
17:
18: /** format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT"
19: */
20: public final static String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
21:
22: // format for RFC 1036 date string -- "Sunday, 06-Nov-94 08:49:37 GMT"
23: public final static String rfc1036Pattern = "EEEEEEEEE, dd-MMM-yy HH:mm:ss z";
24:
25: // format for C asctime() date string -- "Sun Nov 6 08:49:37 1994"
26: public final static String asctimePattern = "EEE MMM d HH:mm:ss yyyy";
27:
28: /**
29: DateFormat to be used to format dates.
30: */
31: public final static DateFormat rfc1123Format = new SimpleDateFormat(
32: RFC1123_PATTERN, Locale.US);
33:
34: public final static DateFormat rfc1036Format = new SimpleDateFormat(
35: rfc1036Pattern, Locale.US);
36:
37: public final static DateFormat asctimeFormat = new SimpleDateFormat(
38: asctimePattern, Locale.US);
39:
40: /**
41: */
42: public static String format1123(Date d, DateFormat df) {
43: long dt = d.getTime() % 1000;
44: if ((rfc1123DS != null) && (dt == rfc1123Sec))
45: return rfc1123DS;
46: rfc1123DS = df.format(d);
47: rfc1123Sec = dt;
48: return rfc1123DS;
49: }
50:
51: /**
52: Parses a string for a date of the format rfc1123Format, rfc1036Format or asctimeFormat.
53: Returns -1, if any parameter is null or the string is of a not supported format.
54: @return the parsed date in milliseconds
55: */
56: public static long parseDate(String dateString) {
57: DateFormat[] format = { rfc1123Format, rfc1036Format,
58: asctimeFormat };
59: return parseDate(dateString, format);
60: }
61:
62: /**
63: Parses a string for a date of one of the given formats.
64: Returns -1, if any parameter is null or the string is of a not supported format.
65: @return the parsed date in milliseconds
66: */
67: public static long parseDate(String dateString, DateFormat[] format) {
68: if (dateString != null && format != null) {
69: Date date = null;
70: for (int i = 0; i < format.length; i++) {
71: try {
72: date = format[i].parse(dateString);
73: return date.getTime();
74: } catch (ParseException e) {
75: } catch (StringIndexOutOfBoundsException e) {
76: }
77: }
78: }
79: return -1;
80: }
81:
82: private static String rfc1123DS;
83: private static long rfc1123Sec;
84:
85: static {
86: rfc1123Format.setTimeZone(GMT_ZONE);
87: rfc1036Format.setTimeZone(GMT_ZONE);
88: asctimeFormat.setTimeZone(GMT_ZONE);
89: }
90: }
|