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¿
# 1 楼答案
使用以下模式:
yyyy-MM-dd HH:mm:ssXXX
从docs开始:
因此,如果字符串在时区内包含冒号,则应使用3个“X-E”
大写字母Y表示“以周为基础的一年”,而不是常规年份(Y)
# 2 楼答案
tl;博士
用偏移量,卢克
你不需要时区。您的字符串与UTC的偏移量比UTC晚五个小时。这告诉我们一个特定的时刻,时间线上的一个点
ISO 8601
用一个^ {CD1>}替换输入中间的那个空间,以符合ISO 8601。java。时间类默认使用标准格式。因此无需指定格式化模式
OffsetDateTime
解析为
OffsetDateTime
ZonedDateTime
如果您确定该值适用于特定时区,则可以应用
ZoneId
来获得ZonedDateTime
请注意
US/Eastern
是deprecated as a time zone name。现代的方法是Continent/Region
。也许你的意思是America/New_York