有 Java 编程相关的问题?

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

java将日期和时间字符串解析为ZonedDateTime对象

我试图解析一个在已知时区中包含日期和时间的字符串。 字符串具有以下格式:

2019-03-07 00:05:00-05:00

我试过这个:

package com.example.test;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Test {

    public static void main( String[] args ) {

        ZoneId myTimeZone = ZoneId.of("US/Eastern");

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ssXX");

        ZonedDateTime zdt = ZonedDateTime.parse("2019-03-07 00:05:00-05:00", dateTimeFormatter.withZone(myTimeZone));

        System.out.println(zdt);

    }

}

这是引发的异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-07 00:05:00-05:00' could not be parsed at index 19
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
    at com.example.test.Test.main(Test.java:24)
C:\Users\user\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

我正在使用Java1.8.0¿


共 (2) 个答案

  1. # 1 楼答案

    使用以下模式:yyyy-MM-dd HH:mm:ssXXX

    docs开始:

    Offset X and x: ... Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'.

    因此,如果字符串在时区内包含冒号,则应使用3个“X-E”

    大写字母Y表示“以周为基础的一年”,而不是常规年份(Y)

  2. # 2 楼答案

    tl;博士

    OffsetDateTime.parse( 
        "2019-03-07 00:05:00-05:00".replace( " " , "T" ) 
    )
    

    用偏移量,卢克

    你不需要时区。您的字符串与UTC的偏移量比UTC晚五个小时。这告诉我们一个特定的时刻,时间线上的一个点

    ISO 8601

    用一个^ {CD1>}替换输入中间的那个空间,以符合ISO 8601。java。时间类默认使用标准格式。因此无需指定格式化模式

    OffsetDateTime

    解析为OffsetDateTime

    String input = "2019-03-07 00:05:00-05:00".replace( " " , "T" ) ;
    OffsetDateTime odt = OffsetDateTime.parse( input ) ;
    

    ZonedDateTime

    如果您确定该值适用于特定时区,则可以应用ZoneId来获得ZonedDateTime

    请注意US/Easterndeprecated as a time zone name。现代的方法是Continent/Region。也许你的意思是America/New_York

    ZoneId z = ZoneId.of( "America/New_York" ) ;
    ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;