SimpleDateFormat parse is one hour out (using RFC 1123, GMT in summer)

心不动则不痛 提交于 2020-01-02 08:09:40

问题


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.

The code below:

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());
}

Writes out:

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

I got this pattern from apache.http.util.DateUtil so expected it to work [1].

Presumably it's a confusion of whether GMT includes or excludes daylight saving?

I'm using Java(TM) SE Runtime Environment (build 1.6.0_31-b04-415-10M3646, also tested on 1.7.0_71).


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

Edit: as per @oscar-castiblanco's comment, I've changed it to new Date(1000), rather than using 1234ms. The same problem still happens.


回答1:


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"

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



回答2:


GMT does not have daylight saving. Here in the UK, we live by "British Standard Time", which has daylight saving. "Greenwich Mean Time" is the world reference time, which does not have daylight saving. However, Microsoft gets this wrong, which has helped to sow confusion.



来源:https://stackoverflow.com/questions/10584647/simpledateformat-parse-is-one-hour-out-using-rfc-1123-gmt-in-summer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!