简体   繁体   English

SimpleDateFormat将lenient设置为false的异常

[英]SimpleDateFormat Exception on setting lenient to false

Why is this code throwing exception of unparseable date? 为什么这段代码会抛出不可解析日期的异常?

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
f.setLenient(false);
String dateStr = "2012-03-11T02:46:01.000Z";
f.parse(dateStr);

It works fine when lenient is true. 当宽松是真的时,它工作正常。 It strangely works for input date ' 2012-03-01T02:46:01.000Z ' even with lenient as false. 它奇怪地适用于输入日期' 2012-03-01T02:46:01.000Z ',即使宽松为假。 Default timezone being used : PST 使用的默认时区:PST

Because that time does not exist in your default time zone—it was daylight savings time change day, and time jumped from 2:00 am to 3:00 am, so there was no 2:46 that morning. 因为在您的默认时区中不存在该时间 - 它是夏令时更改日,并且时间从凌晨2:00跳到凌晨3:00,所以那天早上没有2:46。 :P :P

Since you're parsing UTC, set the SimpleDateFormat instance time zone to UTC like so: 由于您正在解析UTC,因此将SimpleDateFormat实例时区设置为UTC,如下所示:

f.setTimeZone(TimeZone.getTimeZone("UTC"));

and your problem will go away. 你的问题就会消失

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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