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

标签 java java-8 zoneddatetime java-time

我正在尝试解析具有已知时区的日期和时间的字符串。 字符串具有以下格式:

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)

我使用的是 Java 1.8.0_191。

最佳答案

使用此模式: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-es”。

大写的 Y 表示“基于周的年份”,而不是常规的 (y)。

关于java - 将日期和时间字符串解析为 ZonedDateTime 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55072905/

相关文章:

java - 如何将java连接到ms access

java - 使用 Tomcat 或 Node.js 的 RESTful API?

Java 8 模式匹配?

java - 时区 BST 的偏移量错误

java - 将字符串 ("2022-12-23T07:20:00") 时间转换为 ZonedDateTime

java - 检测逻辑连接器的最佳方法

c# - Java 中的 Windows 身份验证

java - Java 8 `Stream` 可以在您不要求的情况下并行吗?

sql-server-2005 - com/microsoft/sqlserver/jdbc/SQLServerDriver 已由更新版本的 Java 运行时编译

java.time.format.DateTimeParseException : Text '2021-02-19T00:45:09.798Z' could not be parsed, 在索引 23 处找到未解析的文本