0
votes

I am retrieving the Last-Modified value of HTTP response header and attempting to convert the String date value to Date object as:

  ..

  URLConnection urlConnection = url.openConnection();
  Map<String, List<String>> headers = urlConnection.getHeaderFields();
  Date date = new SimpleDateFormat("MMMM d, yyyy",   Locale.ENGLISH).parse(headers.get(LAST_MODIFIED).get(0));

This is throwing the exception:

java.text.ParseException: Unparseable date: "Thu, 27 Oct 2011 13:09:24 GMT" at java.text.DateFormat.parse(DateFormat.java:337)

Can someone spot the issue with this?! Thanks.

EDITED.

4
possible duplicate of Java string to date conversionBitmap

4 Answers

3
votes

You need to supply the proper pattern to SimpleDateFormat.

E: Day in week
d: Day in month
M: Month in year
y: Year
H: Hour in day (0-23)
m: Minute in hour
s: Second in minute
z: Time Zone

String dateString = "Thu, 27 Oct 2011 13:09:24 GMT";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date d = format.parse(dateString);

Take a look at this duplicate question: How to parse Date from HTTP Last-Modified header?.

Apache commons-httpclient provides DateUtil.parseDate(dateString) with already uses this format, as Bohzo pointed out in his solution to the linked question

2
votes

Just use urlConnection.getLastModified() and convert that long to a date or Calendar.

1
votes

Shouldn't you be using urlConnection.getDate() to retrieve the value of the Date header? It looks like your retrieving the CONTENT_TYPE header field.

0
votes

The date format you have specified does not match the date format in the string you are parsing.
try:

EEE, dd MMM, yyyy