Java8 DateTimeFormatter am/pm

Noz*_*rum 12 java java-8 java-time

我试图解析一些日期,但DateTimeParser似乎不同意我的有效期

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

ZonedDateTime.parse("Wed Jul 16, 2016 4:38pm EDT", DateTimeFormatter.ofPattern("EEE MMM dd, yyyy hh:mma z", Locale.US))
Run Code Online (Sandbox Code Playgroud)

当我试着这样说时

java.time.format.DateTimeParseException: Text 'Wed Jul 16, 2016 4:38pm EDT' could not be parsed at index 17
Run Code Online (Sandbox Code Playgroud)

那么小时有问题吗?当我放下其中一个'h'时它会进一步增加(尽管它应该只用0-pad我的小时),但是它不喜欢pm-stuff

ZonedDateTime.parse("Wed Jul 16, 2016 4:38pm EDT", DateTimeFormatter.ofPattern("EEE MMM dd, yyyy h:mma z", Locale.US))
java.time.format.DateTimeParseException: Text 'Wed Jul 16, 2016 4:38pm EDT' could not be parsed at index 21
Run Code Online (Sandbox Code Playgroud)

我不知道他的确切问题是什么.当我尝试'hh:mmaa'作为模式时它表示它不喜欢两个a而现在我被卡住了,因为错误消息没有帮助.

ass*_*ias 16

a期望无论PMAM大写.要获得不区分大小写的格式化程序,您需要手动构建它:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("EEE MMM dd, yyyy h:mma z")
        .toFormatter(Locale.US);
Run Code Online (Sandbox Code Playgroud)

请注意,您将收到一个新错误,因为7月16日不是星期三.


Mat*_*hew 7

AM请注意,和的大小写PM取决于您的区域设置!

因此,如果您的区域设置是美国,则预计为大写,但如果是英国,则预计为小写。

请参阅:将时间戳中的周期 (AM/PM) 本地化为另一种语言以了解更多详细信息。