SimpleDateFormat解析是一个小时(在夏天使用RFC 1123,GMT) [英] SimpleDateFormat parse is one hour out (using RFC 1123, GMT in summer)
问题描述
我使用SimpleDateFormat和RFC 1123来格式化日期,并解析日期。但是,解析(格式(日期))有时与原始日期不同一小时。
I am using SimpleDateFormat with RFC 1123 to format dates, and to parse dates. However, parse(format(date)) is sometimes one hour different from the original date.
以下代码:
public static void main(String[] args) throws ParseException {
String RFC1123_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss zzz";
SimpleDateFormat dateFormat = new SimpleDateFormat(RFC1123_DATE_PATTERN);
Date date = new Date(1000);
String str = dateFormat.format(date);
Date date2 = dateFormat.parse(str);
System.out.println("date="+date+"; "+date.getTime());
System.out.println("str="+str);
System.out.println("date2="+date2+"; "+date2.getTime());
}
写出:
date=Thu Jan 01 01:00:01 GMT 1970; 1000
str=Thu, 01 Jan 1970 01:00:01 GMT
date2=Thu Jan 01 02:00:01 GMT 1970; 3601000
我从apache.http.util.DateUtil获得了这个模式,所以期望它能够正常工作[1] 。
I got this pattern from apache.http.util.DateUtil so expected it to work [1].
据推测,GMT是否包含或不包括夏令时的混淆?
Presumably it's a confusion of whether GMT includes or excludes daylight saving?
我正在使用Java( TM)SE运行时环境(版本1.6.0_31-b04-415-10M3646,也在1.7.0_71测试)。
I'm using Java(TM) SE Runtime Environment (build 1.6.0_31-b04-415-10M3646, also tested on 1.7.0_71).
解决方法是使用模式EEE,dd MMM yyyy HH:mm:ss Z,它给出:
A workaround is to use the pattern "EEE, dd MMM yyyy HH:mm:ss Z", which gives:
date=Thu Jan 01 01:00:01 GMT 1970; 1000
str=Thu, 01 Jan 1970 01:00:01 +0100
date2=Thu Jan 01 01:00:01 GMT 1970; 1000
[1] http://www.docjar.com/html/api/org/apache/http/util/DateUtils.java.html
编辑:根据@ oscar-castiblanco的评论,我已将其更改为新日期(1000)
,而不是使用1234ms。同样的问题仍然存在。
as per @oscar-castiblanco's comment, I've changed it to new Date(1000)
, rather than using 1234ms. The same problem still happens.
推荐答案
我尝试了第一种模式EEE,dd MMM yyyy HH:mm:ss zzz和我得到了这个答案
I try the first pattern "EEE, dd MMM yyyy HH:mm:ss zzz" and I got this answer
date=Thu Jan 01 01:00:01 CET 1970; 1234
str=Thu, 01 Jan 1970 01:00:01 CET
date2=Thu Jan 01 01:00:01 CET 1970; 1000
我尝试了第二种模式,得到了相同的答案。
I try the second pattern and I got the same answer.
为了在两种情况下都有相同的时间,我将转换的缺失毫秒添加到模式中:
In order to have the same time in both cases I add the missing milliseconds of the transformation to the patter:
pattern =EEE,dd MMM yyyy HH:mm:ss:SSS Z
pattern = "EEE, dd MMM yyyy HH:mm:ss:SSS Z"
date=Thu Jan 01 01:00:01 CET 1970; 1234
str=Thu, 01 Jan 1970 01:00:01:234 +0100
date2=Thu Jan 01 01:00:01 CET 1970; 1234
这篇关于SimpleDateFormat解析是一个小时(在夏天使用RFC 1123,GMT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!