levanovd
levanovd

Reputation: 4165

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?

Upvotes: 64

Views: 54294

Answers (5)

ralfstx
ralfstx

Reputation: 4023

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.5.x/current/httpclient/apidocs/org/apache/http/client/utils/DateUtils.html

https://github.com/apache/httpcomponents-client/blob/4.5.x/httpclient/src/main/java/org/apache/http/client/utils/DateUtils.java

Date date = DateUtils.parseDate( headerValue );

Upvotes: 25

Stan Svec
Stan Svec

Reputation: 499

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.

Upvotes: 40

Bozho
Bozho

Reputation: 597076

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.

Upvotes: 64

Shaun
Shaun

Reputation: 1508

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

Upvotes: 78

Jin Kwon
Jin Kwon

Reputation: 21978

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.

Upvotes: 5

Related Questions