我正在检索HTTP响应标头的Last-Modified值并尝试将String日期值转换为Date对象:
..
URLConnection urlConnection = url.openConnection();
Map> headers = urlConnection.getHeaderFields();
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(headers.get(LAST_MODIFIED).get(0));
这是抛出异常:
java.text.ParseException: Unparseable date:"Thu, 27 Oct 2011 13:09:24
GMT" at java.text.DateFormat.parse(DateFormat.java:337)
有人能发现这个问题吗?! 谢谢。
编辑。
Java字符串到日期转换的可能重复
您需要为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);
看看这个重复的问题:如何解析HTTP Last-Modified标题中的日期?
Apache commons-httpclient提供的DateUtil.parseDate(dateString)已经使用了这种格式,正如Bohzo在他对链接问题的解决方案中指出的那样
只需使用urlConnection.getLastModified()并将其转换为日期或日历即可。
您不应该使用urlConnection.getDate()来检索Date标头的值吗? 看起来您正在检索CONTENT_TYPE标头字段。
见编辑。 urlConnection.getDate()将返回当前日期。
正如javadoc所说:Returns the value of the date header field.,这与LastModified标头不同。
您指定的日期格式与您要解析的字符串中的日期格式不匹配。
尝试:
EEE, dd MMM, yyyy