Unparseable Date In America/Mazatlan timezone

2019-05-10 04:17发布

I'm on America/Los_Angeles TZ, and when I try to render midnight in the America/Mazatlan TZ, I get the following exception:

Exception in thread "main" java.text.ParseException: Unparseable date: "12:00 AM"

Here is my code to reproduce this:

    DateFormat dateFormat = new SimpleDateFormat("h:mm a");
    TimeZone timeZone = TimeZone.getTimeZone("America/Mazatlan");
    dateFormat.setTimeZone(timeZone);
    dateFormat.setLenient(false);
    Date parse = dateFormat.parse("12:00 AM");

I'm aware the commenting out the setLenient(false) will fix the issue, I'm just not sure why that is a fix as other timezones in the same offset, such as America/Inuvik do not cause issues like this.

Any assistance would be great.

3条回答
叼着烟拽天下
2楼-- · 2019-05-10 04:54

When you don't specify a date, 1970-01-01 is used.

The time zone definition for Mazatlan shows that the base offset switched from -08:00 to -07:00 in 1970. This creates a discontinuity in local time, similar to the kind usually found during a spring-forward daylight saving time transition.

There is an hour of missing local time, from midnight to just before 1:00. Times in this range are invalid. Assuming the zone definition is correct, that means the clocks ticked forward like this:

======== UTC =======     ==== America/Mazatlan ===
1970-01-01T07:59:57Z     1969-12-31T23:59:57-08:00
1970-01-01T07:59:58Z     1969-12-31T23:59:58-08:00
1970-01-01T07:59:59Z     1969-12-31T23:59:59-08:00   
1970-01-01T08:00:00Z     1970-01-01T01:00:00-07:00  (transition!)
1970-01-01T08:00:01Z     1970-01-01T01:00:01-07:00
1970-01-01T08:00:02Z     1970-01-01T01:00:02-07:00

Therefore, if you are using SimpleDateFormat - you should include a date, not just a time.

查看更多
混吃等死
3楼-- · 2019-05-10 04:57

That because you dateFormat.setLenient(false); and 12:00 should be 'PM' not 'AM'

查看更多
别忘想泡老子
4楼-- · 2019-05-10 04:58

If you remove the line,

    dateFormat.setLenient(false);

Your parse object value is becoming

     Thu Jan 01 10:00:00 EET 1970

I don't know why but for America/Mazatlan TZ this line is creating exception.

For America/Los_Angeles TZ and America/Inuvik TZ, usage of dateFormat.setLenient(false) line not giving any error and results are the same with America/Mazatlan TZ.

    Thu Jan 01 10:00:00 EET 1970
查看更多
登录 后发表回答