views:

747

answers:

3

HTTP Last-Modified header contains date in following format (example):
Wed, 09 Apr 2008 23:55:38 GMT
What is the easiest way to parse java.util.Date from this string?

+5  A: 

This should be pretty close

String dateString = "Wed, 09 Apr 2008 23:55:38 GMT";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date d = format.parse(dateString);

SimpleDateFormat

Shaun
+1 almost correct, the `hh` should be `HH`, as the hours are 0-23.
notnoop
Good catch, fixed now
Shaun
I also had the timezone "ZZZ" instead of "zzz". Hopefully that will do it. If you still have issues you can reference the documentation linked above.
Shaun
Works great for me, thank you! The only thing that I should say is that this example is for Locale.ENGLISH.
levanovd
If you're doing this often make sure you reuse the SimpleDateFormat object (they're amazingly expensive to construct) and synchronize on it when calling `parse` (they're not threadsafe).
Ry4an
The standard allows not one format, but **three** formats. http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
Sridhar Ratnakumar
+4  A: 

DateUtil.parseDate(dateString) (from apache commons-httpclient)

It has the correct format defined as a Constant, which is guarnateed to be compliant with the protocol.

Bozho
+1 beat me to it :)
ZoogieZork
+1  A: 

RFC 2616 defines three different date formats that a conforming client must understand.

The Apache HttpClient provides a DateUtil that complies with the standard: http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/impl/cookie/DateUtils.html

Date date = DateUtil.parseDate( headerValue );

ralfstx