Failed to parse single digit hour and lowercase am-pm of day into Java 8 LocalTime

前端 未结 6 2008
借酒劲吻你
借酒劲吻你 2021-01-05 10:50

When I try to run the following code:

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

I get this:

6条回答
  •  佛祖请我去吃肉
    2021-01-05 11:07

    The AM/PM tokens have* to be uppercase:

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

    Patterns definitions for hours:

    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
    

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

    -- EDIT

    *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:

    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)

提交回复
热议问题