我在将字符串格式化为ZonedDateTime时遇到问题。我的客户希望日期采用 ddMMyyhhmmss 等格式,没有分隔符或类似的东西。这是我到目前为止所做的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 变量的解析过程中28032019100707Exception 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)在SO上搜索,我看到同一问题的一些答案建议使用LocalDateTime类作为中间类,然后解析为ZonedDateTime,但它仍然不起作用,抛出了相同的错误。我还尝试使用此过程更改初始化DateTimeFormatter的方式DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyyhhmmss") .toFormatter() .withZone(ZoneId.systemDefault());但它仍然不起作用。我知道我肯定错过了一些愚蠢的东西,但我看不到什么。任何人都可以给我指出正确的方向吗?
3 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
在您解析的字符串中,没有关于时区的信息 - 那么格式化程序应该如何知道如何转换为ZonedDateTime?
您需要在字符串中包含时区信息,或者使用另一个对象将其解析为没有时区信息,然后将其传输到所需的区域中。
添加回答
举报
0/150
提交
取消
