简体   繁体   中英

Date conversion: error with time

I got a date from server in the form E, dd MMM yyyy HH:mm:ss Z where timezone is +0200

I parse it in my own format yyyy-MM-dd HH:mm:ss using

myFormat.format(serverFormat.parse(dateString));

and I get time wrong: it's one hour before. So, if I get 10:00 in conversion I get 09:00 . Why?

I believe that the problem here is DST - Daylight saving time. The standard is winter time. It is a summer now, so you get 1 hour difference. You are using timezone shift syntax +0200 that does not and cannot support daylight saving because it depends on country.

You should use locale specific syntax of time zone definition, eg Europe/Amsterdam instead of +0100 . In addition take a look on API of class TimeZone :

  • inDaylightTime(Date date)
  • useDaylightTime()

Check the timezone of the returned value which most probably is the cause of the issue.

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");    
formatter.setTimeZone(TimeZone.getTimeZone("GMT+2")); 

System.out.println( formatter.format(serverFormat.parse(dateString));

试试吧

formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM