【发布时间】:2019-08-19 01:35:56
【问题描述】:
我在将字符串格式化为 ZonedDateTime 时遇到问题。
我的客户希望日期格式为 ddMMyyyyhhmmss,没有分隔符或类似的东西。
这是我到目前为止所做的
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class MyClass {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyhhmmss");
String test = formatter
.format(ZonedDateTime.now()).toString();
System.out.println(test);
ZonedDateTime a = ZonedDateTime.parse(test,formatter);
System.out.println(a.toString());
}
}
虽然它正确生成字符串,但在创建 LocalDateTime 变量的解析过程中会出现错误
28032019100707
Exception in thread "main" java.time.format.DateTimeParseException: Text '28032019100707' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=7, HourOfAmPm=10, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=7},ISO resolved to 2019-03-28 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at MyClass.main(MyClass.java:14)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=7, HourOfAmPm=10, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=7},ISO resolved to 2019-03-28 of type java.time.format.Parsed
at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=7, HourOfAmPm=10, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=7},ISO resolved to 2019-03-28 of type java.time.format.Parsed
at java.time.ZoneId.from(ZoneId.java:466)
at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
... 4 more
Command exited with non-zero status 1
搜索 SO,我看到对同一问题的一些答案建议使用 LocalDateTime 类作为中间,然后解析为 ZonedDateTime 但它仍然无法正常工作,抛出相同的错误。 我也尝试过改变我用这个过程初始化 DateTimeFormatter 的方式
DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyyhhmmss")
.toFormatter()
.withZone(ZoneId.systemDefault());
但它仍然无法正常工作。我知道我肯定错过了一些愚蠢的东西,但我看不出是什么。谁能指出我正确的方向?
【问题讨论】:
-
此外,格式模式字符串中的一天中的小时需要大写
HH,例如 this question。 -
@OleV.V.即使它不能解决我的问题,您认为它是否相关?我只是问这样,下次我可以避免提出类似的问题
-
没错:字符串没有包含足够的信息,
ZonedDateTime无法解析回相同的值。 -
@OleV.V.不过,谢谢您解释为什么将其标记为重复 :)
标签: java date datetime time zoneddatetime