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)
我正在使用 Java 1.8.0_191。
解决方案
使用此模式:yyyy-MM-dd HH:mm:ssXXX
从文档:
偏移量 X 和 x:... 两个字母输出小时和分钟,不带冒号,例如 '+0130'。三个字母输出小时和分钟,带有冒号,例如'+01:30'。
因此,如果您的字符串在时区内包含冒号,则应使用 3 个“X-es”。
大写 Y 的意思是“以周为基础的年”,而不是常规的 (y)。
推荐阅读
- statistics - 为什么序列相关仍然会产生无偏且一致的参数
- java - 效率:HashMap 检查 containsKey() vs always put()
- angular - 我怎样才能最好地解决 Angular 教程中的这个错误?
- python - 重叠前缀词正则表达式
- python - 如何在python中将变量传递给argparse
- c - 使用 fgets 从 START 到 STOP 字符串读取所有文件字符
- javascript - 将我的 Mobx 存储写在单独的文件中还是在 React 组件中更好?
- python - 如何使用 conda 选择要下载的特定版本的软件包?
- python - 如何为 scipy 最小化创建目标函数
- x86 - 在当前指令后监视陷阱标志 VM 退出