View Javadoc

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateUtil.java,v 1.2 2004/12/24 20:36:13 olegk Exp $
3    * $Revision: 224451 $
4    * $Date: 2005-07-23 06:23:59 -0400 (Sat, 23 Jul 2005) $
5    *
6    * ====================================================================
7    *
8    *  Copyright 1999-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.util;
31  
32  import java.text.ParseException;
33  import java.text.SimpleDateFormat;
34  import java.util.Arrays;
35  import java.util.Calendar;
36  import java.util.Collection;
37  import java.util.Date;
38  import java.util.Iterator;
39  import java.util.Locale;
40  import java.util.TimeZone;
41  
42  /***
43   * A utility class for parsing and formatting HTTP dates as used in cookies and 
44   * other headers.  This class handles dates as defined by RFC 2616 section 
45   * 3.3.1 as well as some other common non-standard formats.
46   * 
47   * @author Christopher Brown
48   * @author Michael Becke
49   */
50  public class DateUtil {
51  
52      /***
53       * Date format pattern used to parse HTTP date headers in RFC 1123 format.
54       */
55      public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
56  
57      /***
58       * Date format pattern used to parse HTTP date headers in RFC 1036 format.
59       */
60      public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
61  
62      /***
63       * Date format pattern used to parse HTTP date headers in ANSI C 
64       * <code>asctime()</code> format.
65       */
66      public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
67  
68      private static final Collection DEFAULT_PATTERNS = Arrays.asList(
69      		new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
70      
71      private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
72      
73      static {
74          Calendar calendar = Calendar.getInstance();
75          calendar.set(2000, Calendar.JANUARY, 1, 0, 0);
76          DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); 
77      }
78      
79      private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
80      
81      /***
82       * Parses a date value.  The formats used for parsing the date value are retrieved from
83       * the default http params.
84       *
85       * @param dateValue the date value to parse
86       * 
87       * @return the parsed date
88       *
89       * @throws DateParseException if the value could not be parsed using any of the 
90       * supported date formats
91       */
92      public static Date parseDate(String dateValue) throws DateParseException {
93          return parseDate(dateValue, null, null);
94      }
95      
96      /***
97       * Parses the date value using the given date formats.
98       * 
99       * @param dateValue the date value to parse
100      * @param dateFormats the date formats to use
101      * 
102      * @return the parsed date
103      * 
104      * @throws DateParseException if none of the dataFormats could parse the dateValue
105      */
106     public static Date parseDate(String dateValue, Collection dateFormats) 
107         throws DateParseException {
108         return parseDate(dateValue, dateFormats, null);
109     }
110     
111     /***
112      * Parses the date value using the given date formats.
113      * 
114      * @param dateValue the date value to parse
115      * @param dateFormats the date formats to use
116      * @param startDate During parsing, two digit years will be placed in the range 
117      * <code>startDate</code> to <code>startDate + 100 years</code>. This value may 
118      * be <code>null</code>. When <code>null</code> is given as a parameter, year 
119      * <code>2000</code> will be used. 
120      * 
121      * @return the parsed date
122      * 
123      * @throws DateParseException if none of the dataFormats could parse the dateValue
124      */
125     public static Date parseDate(
126         String dateValue, 
127         Collection dateFormats,
128         Date startDate 
129     ) throws DateParseException {
130         
131         if (dateValue == null) {
132             throw new IllegalArgumentException("dateValue is null");
133         }
134         if (dateFormats == null) {
135         	dateFormats = DEFAULT_PATTERNS;
136         }
137         if (startDate == null) {
138             startDate = DEFAULT_TWO_DIGIT_YEAR_START;
139         }
140         // trim single quotes around date if present
141         // see issue #5279
142         if (dateValue.length() > 1 
143             && dateValue.startsWith("'") 
144             && dateValue.endsWith("'")
145         ) {
146             dateValue = dateValue.substring (1, dateValue.length() - 1);
147         }
148         
149         SimpleDateFormat dateParser = null;        
150         Iterator formatIter = dateFormats.iterator();
151         
152         while (formatIter.hasNext()) {
153             String format = (String) formatIter.next();            
154             if (dateParser == null) {
155                 dateParser = new SimpleDateFormat(format, Locale.US);
156                 dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
157                 dateParser.set2DigitYearStart(startDate);
158             } else {
159                 dateParser.applyPattern(format);                    
160             }
161             try {
162                 return dateParser.parse(dateValue);
163             } catch (ParseException pe) {
164                 // ignore this exception, we will try the next format
165             }                
166         }
167         
168         // we were unable to parse the date
169         throw new DateParseException("Unable to parse the date " + dateValue);        
170     }
171 
172     /***
173      * Formats the given date according to the RFC 1123 pattern.
174      * 
175      * @param date The date to format.
176      * @return An RFC 1123 formatted date string.
177      * 
178      * @see #PATTERN_RFC1123
179      */
180     public static String formatDate(Date date) {
181         return formatDate(date, PATTERN_RFC1123);
182     }
183     
184     /***
185      * Formats the given date according to the specified pattern.  The pattern
186      * must conform to that used by the {@link SimpleDateFormat simple date
187      * format} class.
188      * 
189      * @param date The date to format.
190      * @param pattern The pattern to use for formatting the date.  
191      * @return A formatted date string.
192      * 
193      * @throws IllegalArgumentException If the given date pattern is invalid.
194      * 
195      * @see SimpleDateFormat
196      */
197     public static String formatDate(Date date, String pattern) {
198         if (date == null) throw new IllegalArgumentException("date is null");
199         if (pattern == null) throw new IllegalArgumentException("pattern is null");
200         
201         SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
202         formatter.setTimeZone(GMT);
203         return formatter.format(date);
204     }
205     
206     /*** This class should not be instantiated. */    
207     private DateUtil() { }
208     
209 }