简体   繁体   中英

Java SimpleDateFormat parsing irregularities

I'm doing some date parsing in Java and am encountering some weird behavior.

I have a date string such as follows:

String s = "Sun Aug 11 2013 11:00:00 -0700 (Pacific Daylight Time)"

I'm trying to parse it into a date object like so:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z (zzzz)");

I then print out the resulting date object from sdf.parse(s) and get:

Sun Aug 11 12:00:00 CDT 2013

I am in the central time zone, so it makes sense that it prints it as such, however, CDT is -0500, so the parsed date should be 13:00, not 12:00.

The odd thing is, if I remove either of the redundant pieces of time zone information, the date parses correctly. Using the format "EEE MMM dd yyyy HH:mm:ss Z ('Pacific Daylight Time')" or the format "EEE MMM dd yyyy HH:mm:ss '-0700' (zzzz)" results in the correct date:

Sun Aug 11 13:00:00 CDT 2013

This behavior seems to only occur with dates that fall within daylight savings time. If I instead parse a date in, say, December, with my initial date format, I get the correct result.

I have somewhat limited control over the format of the dates I'm parsing, and they could be coming from a variety of time zones. Has anyone encountered this behavior before, and is there a way to get around it without changing the format of the date string? I realize the time zone designations are redundant, but they aren't incorrect as far as I can tell.

There have certainly been bugs in Java's handling of daylight saving time and time zones in the past, and this sure looks like one you've found. What version of Java is this?

You might want to try giving Joda-Time a try to see if it handles the given date correctly.

If Joda doesn't help, you might need to try pre-parsing some of that date string to remove the descriptive time zone in parenthesis since it works when only one is defined. Very strange indeed!

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