Java 为什么使用 SimpleDateFormat("hh:mm aa") 解析“23:00 PM”会返回上午 11 点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1154903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:19:16  来源:igfitidea点击:

Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa") return 11 a.m.?

javadatetimesimpledateformat

提问by OscarRyz

Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa")return 11 a.m.?

为什么在SimpleDateFormat("hh:mm aa")上午 11 点解析“23:00 PM” ?

采纳答案by Hyman Leow

You should be getting an exception, since "23:00 PM" is not a valid string, but Java's date/time facility is lenientby default, when handling date parsing.

你应该得到一个异常,因为“23:00 PM”不是一个有效的字符串,但在处理日期解析时,Java 的日期/时间工具默认是宽松的。

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).

逻辑是 23:00 PM 是 11:00 PM 之后的 12 小时,也就是第二天的上午 11:00。您还会看到诸如“4 月 31 日”之类的内容被解析为“5 月 1 日”(4 月 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.

如果您不希望出现这种行为,请使用DateFormat#setLenient(boolean)在 SimpleDateFormat上将 lenient属性设置为 false ,并且在传入无效日期/时间时会出现异常。

回答by Evan Teran

I would guess that it does something like:

我猜它会做类似的事情:

hours = hours % 12;

to ensure that the hours are in the proper range.

以确保时间在适当的范围内。

回答by Steve McLeod

You want "HH:mm aa" as your format, if you will be parsing 24-hour time.

如果您要解析 24 小时制,您需要“HH:mm aa”作为您的格式。

public static void main(String[] args) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("HH:mm aa");
    final Date date = df.parse("23:00 PM");
    System.out.println("date = " + df.format(date));
}

outputs

产出

date = 23:00 PM

回答by thelsdj

Have you tried HH:mm aa?

你试过HH:mm aa吗?

HHis for 24 hour while hhis for 12.

HH是 24 小时,而hh12小时。

回答by Greg

23:00 PM could be thought of as 11 AM the next day. Javascript and PHP work like this pretty much but I can't speak for Java.

23:00 PM 可以被认为是第二天上午 11 点。Javascript 和 PHP 的工作方式差不多,但我不能说 Java。

回答by Peter Recore

Here are the formatting options specifed in the javadoc

以下是javadoc 中指定的格式选项

H     Hour in day (0-23)    
k   Hour in day (1-24)  
K   Hour in am/pm (0-11)    
h   Hour in am/pm (1-12) 

Notice that "h" would be for hours 1-12. If you want to handle 1-24, try "k". for 0-23 try "H". But I would not expect valid results if you are putting in impossible data.

请注意,“h”将表示 1-12 小时。如果要处理 1-24,请尝试“k”。对于 0-23 尝试“H”。但是,如果您输入不可能的数据,我不会期望得到有效的结果。