有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java本地日期时间解析

我正在尝试将输入字符串解析为本地日期时间

下面是我的一段代码

 ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z", MY_DATE_TIME_FORMATTER);

在哪里

MY_DATE_TIME_FORMATTER= new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(ISO_LOCAL_DATE)
            .appendLiteral('T')
            .append(ISO_LOCAL_TIME)
            .appendLiteral('Z')
            .appendOffset("+HH:mm", "+0000")
            .toFormatter();

我得到以下例外

爪哇。时间总体安排DateTimeParseException:无法在索引19处分析文本“2019-11-26T19:30:00Z”

你能告诉我我做错了什么吗


共 (3) 个答案

  1. # 1 楼答案

    Instant.parse

    不需要格式化模式

    Instant.parse( "2019-11-26T19:30:00Z" ) 
    

    您的输入格式符合ISO 8601标准。该特定格式的末尾有一个Z。这个字母的意思是UTC(零小时分秒的offset),发音为“祖鲁”

    java中的Instant类。时间表示UTC中的一个时刻,始终为UTC

    对该输入使用ZonedDateTime类不是最合适的。我们有:

    • ^{}用于始终以UTC为单位的值
    • ^{}仅知道UTC的偏移量而不知道时区的时刻。当您需要更大的灵活性(如生成各种格式的字符串)时,也可以将此类用于UTC值`瞬间原子偏移(
    • ^{}用于时区中的值。时区是特定地区人民使用的偏移量的过去、现在和未来变化的历史

    Table of date-time types in Java, both modern and legacy

    要查看调整为特定区域(时区)的人使用的偏移量的同一时刻,请应用ZoneId获取ZonedDateTime对象

    Instant instant = Instant.parse( "2019-11-26T19:30:00Z" ) ;     // Default format for parsing a moment in UTC.
    ZoneId z = ZoneId.of( "America/Edmonton" ) ;                    // A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.
    ZonedDateTime zdt = instant.atZone( z ) ;                       // Same moment, same point on the timeline, different wall-clock time.
    

    见此code run live at IdeOne.com

    instant.toString(): 2019-11-26T19:30:00Z

    zdt.toString(): 2019-11-26T12:30-07:00[America/Edmonton]

  2. # 2 楼答案

    .appendZoneOrOffsetId()
    

    而不是这两行:

    .appendLiteral('Z')
    .appendOffset("+HH:mm", "+0000")
    

    整个生成器示例:

    MY_DATE_TIME_FORMATTER= new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(ISO_LOCAL_DATE)
            .appendLiteral('T')
            .append(ISO_LOCAL_TIME)
            .appendZoneOrOffsetId()
            .toFormatter();
    

    另外,在您的具体情况下,我宁愿使用标准ISO格式化程序(如Hristo所述):

    ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z", DateTimeFormatter.ISO_ZONED_DATE_TIME);
    

    此外,即使没有显式格式化程序,ZonedDateTime::parse方法也可以工作。因为它是默认使用的:

    ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z");
    
  3. # 3 楼答案

    使用内置的ISO分区时间格式化程序

        ZonedDateTime.parse("2019-11-26T19:30:00Z", DateTimeFormatter.ISO_ZONED_DATE_TIME);