无法将单个数字小时和小写的am-pm解析为Java 8 LocalTime [英] Failed to parse single digit hour and lowercase am-pm of day into Java 8 LocalTime

查看:439
本文介绍了无法将单个数字小时和小写的am-pm解析为Java 8 LocalTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行以下代码时:

When I try to run the following code:

LocalTime test = LocalTime.parse("8:00am", DateTimeFormatter.ofPattern("hh:mma"));

我明白了:

Exception in thread "main" java.time.format.DateTimeParseException: Text '8:00am' could not be parsed at index 0

知道为什么会这样吗?

推荐答案

上午/下午令牌*为大写:

The AM/PM tokens have* to be uppercase:

LocalTime test = LocalTime.parse("8:00AM", DateTimeFormatter.ofPattern("hh:mma"));

小时的模式定义:

Symbol  Meaning                     Presentation      Examples
------  ------------                ------------      --------
a       am-pm-of-day                text              PM
h       clock-hour-of-am-pm (1-12)  number            12
K       hour-of-am-pm (0-11)        number            0
k       clock-hour-of-am-pm (1-24)  number            0
H       hour-of-day (0-23)          number            0

请参阅所有可用模式的 DateTimeFormatter javadocs: https://docs.oracle.com/javase/8/docs /api/java/time/format/DateTimeFormatter.html

Refer to the DateTimeFormatter javadocs for all available patterns: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

- 编辑

*根据@ Hugo的评论,这与区域设置。如果未指定任何内容,则使用JVM默认值。事实上,绝大多数Locales都强制AM / PM令牌为大写:

*As per @Hugo's comment, this is related to the Locale your formatter is setup on. If you are not specifying any, then the JVMs default is used. It just happens that the vast majority of Locales enforces AM/PM tokens to be upper case:


对于大多数语言环境而言,恰好如此使用大写的AM,因此它适用于大多数人。但它也可以是ga_IE和es_US语言环境中的a.m.,日语中的午前(ja_JP),瑞典语中的fm(sv_SE)以及许多其他语言。我已经在JDK 1.8.0_144中进行了测试,它有160个语言环境 - 其中108个使用AM - 无论如何,如果你的JVM使用其中一个语言环境(并且没有人更改此配置),这不是问题。

It so happens that, for most locales, the uppercase AM is used, so it'll work for most people. But it can also be a.m. in ga_IE and es_US locales, 午前 in Japanese (ja_JP), fm in Swedish (sv_SE), and many others. I've tested in JDK 1.8.0_144 and it has 160 locales - 108 of them use AM - anyway, it's not an issue if your JVM uses one of those 108 locales (and nobody changes this config)

这篇关于无法将单个数字小时和小写的am-pm解析为Java 8 LocalTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆