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: 190480 $
4    * $Date: 2005-06-13 14:45:24 -0400 (Mon, 13 Jun 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  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  /***
46   * A utility class for parsing and formatting HTTP dates as used in cookies and 
47   * other headers.  This class handles dates as defined by RFC 2616 section 
48   * 3.3.1 as well as some other common non-standard formats.
49   * 
50   * @author Christopher Brown
51   * @author Michael Becke
52   */
53  public class DateUtil {
54  
55      /*** Log object for this class. */
56      private static final Log LOG = LogFactory.getLog(DateUtil.class);
57  
58      /***
59       * Date format pattern used to parse HTTP date headers in RFC 1123 format.
60       */
61      public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
62  
63      /***
64       * Date format pattern used to parse HTTP date headers in RFC 1036 format.
65       */
66      public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
67  
68      /***
69       * Date format pattern used to parse HTTP date headers in ANSI C 
70       * <code>asctime()</code> format.
71       */
72      public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
73  
74      private static final Collection DEFAULT_PATTERNS = Arrays.asList(
75      		new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
76      
77      private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
78      
79      static {
80          Calendar calendar = Calendar.getInstance();
81          calendar.set(2000, Calendar.JANUARY, 1, 0, 0);
82          DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); 
83      }
84      
85      private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
86      
87      /***
88       * Parses a date value.  The formats used for parsing the date value are retrieved from
89       * the default http params.
90       *
91       * @param dateValue the date value to parse
92       * 
93       * @return the parsed date
94       *
95       * @throws DateParseException if the value could not be parsed using any of the 
96       * supported date formats
97       */
98      public static Date parseDate(String dateValue) throws DateParseException {
99          return parseDate(dateValue, null, null);
100     }
101     
102     /***
103      * Parses the date value using the given date formats.
104      * 
105      * @param dateValue the date value to parse
106      * @param dateFormats the date formats to use
107      * 
108      * @return the parsed date
109      * 
110      * @throws DateParseException if none of the dataFormats could parse the dateValue
111      */
112     public static Date parseDate(String dateValue, Collection dateFormats) 
113         throws DateParseException {
114         return parseDate(dateValue, dateFormats, null);
115     }
116     
117     /***
118      * Parses the date value using the given date formats.
119      * 
120      * @param dateValue the date value to parse
121      * @param dateFormats the date formats to use
122      * @param startDate During parsing, two digit years will be placed in the range 
123      * <code>startDate</code> to <code>startDate + 100 years</code>. This value may 
124      * be <code>null</code>. When <code>null</code> is given as a parameter, year 
125      * <code>2000</code> will be used. 
126      * 
127      * @return the parsed date
128      * 
129      * @throws DateParseException if none of the dataFormats could parse the dateValue
130      */
131     public static Date parseDate(
132         String dateValue, 
133         Collection dateFormats,
134         Date startDate 
135     ) throws DateParseException {
136         
137         if (dateValue == null) {
138             throw new IllegalArgumentException("dateValue is null");
139         }
140         if (dateFormats == null) {
141         	dateFormats = DEFAULT_PATTERNS;
142         }
143         if (startDate == null) {
144             startDate = DEFAULT_TWO_DIGIT_YEAR_START;
145         }
146         // trim single quotes around date if present
147         // see issue #5279
148         if (dateValue.length() > 1 
149             && dateValue.startsWith("'") 
150             && dateValue.endsWith("'")
151         ) {
152             dateValue = dateValue.substring (1, dateValue.length() - 1);
153         }
154         
155         SimpleDateFormat dateParser = null;        
156         Iterator formatIter = dateFormats.iterator();
157         
158         while (formatIter.hasNext()) {
159             String format = (String) formatIter.next();            
160             if (dateParser == null) {
161                 dateParser = new SimpleDateFormat(format, Locale.US);
162                 dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
163                 dateParser.set2DigitYearStart(startDate);
164             } else {
165                 dateParser.applyPattern(format);                    
166             }
167             try {
168                 return dateParser.parse(dateValue);
169             } catch (ParseException pe) {
170                 // ignore this exception, we will try the next format
171             }                
172         }
173         
174         // we were unable to parse the date
175         throw new DateParseException("Unable to parse the date " + dateValue);        
176     }
177 
178     /***
179      * Formats the given date according to the RFC 1123 pattern.
180      * 
181      * @param date The date to format.
182      * @return An RFC 1123 formatted date string.
183      * 
184      * @see #PATTERN_RFC1123
185      */
186     public static String formatDate(Date date) {
187         return formatDate(date, PATTERN_RFC1123);
188     }
189     
190     /***
191      * Formats the given date according to the specified pattern.  The pattern
192      * must conform to that used by the {@link SimpleDateFormat simple date
193      * format} class.
194      * 
195      * @param date The date to format.
196      * @param pattern The pattern to use for formatting the date.  
197      * @return A formatted date string.
198      * 
199      * @throws IllegalArgumentException If the given date pattern is invalid.
200      * 
201      * @see SimpleDateFormat
202      */
203     public static String formatDate(Date date, String pattern) {
204         if (date == null) throw new IllegalArgumentException("date is null");
205         if (pattern == null) throw new IllegalArgumentException("pattern is null");
206         
207         SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
208         formatter.setTimeZone(GMT);
209         return formatter.format(date);
210     }
211     
212     /*** This class should not be instantiated. */    
213     private DateUtil() { }
214     
215 }