How to parse Date from HTTP Last-Modified header?

JavaHttpDateHttp Headers

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

DateUtil.parseDate(dateString) from apache http-components

(legacy: http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/util/DateUtil.html#parseDate%28java.lang.String%29">`DateUtil.parseDate(dateString)`</a> (from apache commons-httpclient))

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

Solution 3 - Java

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.

Solution 4 - Java

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 );

Solution 5 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlevanovdView Question on Stackoverflow
Solution 1 - JavaShaunView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaStan SvecView Answer on Stackoverflow
Solution 4 - JavaralfstxView Answer on Stackoverflow
Solution 5 - JavaJin KwonView Answer on Stackoverflow