SimpleDateFormat parse is one hour out (using RFC

2019-05-13 23:33发布

问题:

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.