Java 如何从 HTTP Last-Modified 标头解析日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1930158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse Date from HTTP Last-Modified header?
提问by levanovd
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.Datefrom this string?
HTTP Last-Modified 标头包含以下格式的日期(示例):从该字符串Wed, 09 Apr 2008 23:55:38 GMT
解析java.util.Date的最简单方法是什么?
采纳答案by Shaun
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);
回答by Bozho
DateUtil.parseDate(dateString)
from apache http-components
DateUtil.parseDate(dateString)
来自 apache http-components
(legacy: DateUtil.parseDate(dateString)
(from apache commons-httpclient))
(遗留:(DateUtil.parseDate(dateString)
来自 apache commons-httpclient))
It has the correct format defined as a Constant, which is guaranteed to be compliant with the protocol.
它具有定义为常量的正确格式,保证符合协议。
回答by ralfstx
RFC 2616 defines three different date formats that a conforming client must understand.
RFC 2616 定义了符合要求的客户端必须理解的三种不同的日期格式。
The Apache HttpClient provides a DateUtil that complies with the standard:
Apache HttpClient 提供了一个符合标准的 DateUtil:
Date date = DateUtils.parseDate( headerValue );
Date date = DateUtils.parseDate( headerValue );
回答by Jin Kwon
If you're using URLConnection
s, there is already a handy method.
如果您使用URLConnection
的是s,那么已经有一个方便的方法了。
See URLConnection#getLastModified
见 URLConnection#getLastModified
This method parses the date string and returns a milliseconds value. Then you can happily create a Date
with that value.
此方法解析日期字符串并返回毫秒值。然后你可以愉快地创建一个Date
具有该值的。
回答by Stan Svec
java.time
时间
When using the new Java Date and Time APIthe code would simply be:
使用新的Java 日期和时间 API 时,代码将是:
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 1123defines that format.
所述DateTimeFormatter
类预定义了该特定格式的恒定RFC_1123_DATE_TIME
。顾名思义,RFC 1123定义了该格式。