为什么用SimpleDateFormat(“hh:mm aa”)解析'23:00 PM'返回上午11点 [英] Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa") return 11 a.m.?
问题描述
为什么用code解析'23:00 PM'?SimpleDateFormat(hh:mm aa) return 11 am?
你应该得到一个例外,因为23:00 PM不是一个有效的字符串,但Java的日期/时间设施是 lenient 默认情况下,处理日期解析时。 p>
逻辑是23:00 PM是在11:00 PM之后12小时,即第二天上午11:00。你也会看到像4月31日被解析为5月1日的事情(4月30日后的一天)。
如果你不想要这个行为,在SimpleDateFormat上使用 DateFormat#setLenient(boolean),当您传递无效的日期/时间时,您将收到异常。
Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa")
return 11 a.m.?
You should be getting an exception, since "23:00 PM" is not a valid string, but Java's date/time facility is lenient by default, when handling date parsing.
The logic is that 23:00 PM is 12 hours after 11:00 PM, which is 11:00 AM the following day. You'll also see things like "April 31" being parsed as "May 1" (one day after April 30).
If you don't want this behavior, set the lenient property to false on your SimpleDateFormat using DateFormat#setLenient(boolean), and you'll get an exception when passing in invalid date/times.
这篇关于为什么用SimpleDateFormat(“hh:mm aa”)解析'23:00 PM'返回上午11点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!