Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Date from HTTP Last-Modified header?

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?

like image 825
levanovd Avatar asked Dec 18 '09 19:12

levanovd


People also ask

Which header of HTTP response provides the last modified date and time of resource?

The Last-Modified response HTTP header contains a date and time when the origin server believes the resource was last modified. It is used as a validator to determine if the resource is the same as the previously stored one.

What is http date format?

2 digit minute number, e.g. "04" or "59". 2 digit second number, e.g. "04" or "59". Greenwich Mean Time. HTTP dates are always expressed in GMT, never in local time.


5 Answers

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

like image 167
Shaun Avatar answered Oct 04 '22 07:10

Shaun


DateUtil.parseDate(dateString) from apache http-components

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

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

like image 22
Bozho Avatar answered Oct 04 '22 05:10

Bozho


java.time

When using the new Java Date and Time API the code would simply be:

ZonedDateTime zdt = ZonedDateTime.parse("Wed, 09 Apr 2008 23:55:38 GMT", DateTimeFormatter.RFC_1123_DATE_TIME);

The DateTimeFormatter class pre-defines a constant for that particular format in RFC_1123_DATE_TIME. As the name suggests, RFC 1123 defines that format.

like image 43
Stan Svec Avatar answered Oct 04 '22 05:10

Stan Svec


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

The Apache HttpClient provides a DateUtil that complies with the standard:

https://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/org/apache/http/client/utils/DateUtils.html

https://apache.googlesource.com/httpclient/+/4.3.x/httpclient/src/main/java/org/apache/http/client/utils/DateUtils.java

Date date = DateUtils.parseDate( headerValue );

like image 29
ralfstx Avatar answered Oct 04 '22 06:10

ralfstx


If you're using URLConnections, there is already a handy method.

See URLConnection#getLastModified

This method parses the date string and returns a milliseconds value. Then you can happily create a Date with that value.

like image 29
Jin Kwon Avatar answered Oct 04 '22 05:10

Jin Kwon