我尝试将字符串从 JSON 转换为 ZonedDateTime,就像
static String getWatchTime(JSONObject aJson, JSONObject bJson) {
long difference = 0 ;
try {
String aTime = aJson.getString("time_utc_8");
String bTime = bJson.getString("time_utc_8");
String pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";
DateTimeFormatter Parser = DateTimeFormatter.ofPattern(pattern).ISO_DATE;
System.out.println(aTime);
ZonedDateTime a = ZonedDateTime.parse(aTime, Parser);
ZonedDateTime b = ZonedDateTime.parse(bTime, Parser);
ChronoUnit unit = null;
difference = unit.between(a, b);
System.out.println(difference);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String t = difference +"";
return t;
}
总是报错
Exception in thread "main" java.time.format.DateTimeParseException: Text '2016-06-28 22:29:44.700228' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2016-06-28T22:29:44.700228 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.OffsetDateTime.parse(Unknown Source)
at Q2.getWatchTime(Q2.java:321)
at Q2.WatchTime(Q2.java:265)
at Q2.main(Q2.java:31)
我想得到这两个日期之间的差异。
我试过 SimpleDateFormat
但它会得到错误结果,对于工厂来说。
最佳答案
我觉得评论里都已经说完了,所以这里只是总结一下。
(1) 您的格式模式字符串是正确的。您只需要从以下行中删除.ISO_DATE
,这样它就变成了:
DateTimeFormatter Parser = DateTimeFormatter.ofPattern(pattern);
(ISO_DATE
接受例如“2011-12-03+01:00”或“2011-12-03”,一个没有时间的日期,有或没有与 UTC 的偏移;你有据我所知,这里没有任何用处。)
(2) 由于您的字符串似乎既没有时区也没有偏移量,因此使用 LocalDateTime
:
LocalDateTime a = LocalDateTime.parse(aTime, Parser);
LocalDateTime b = LocalDateTime.parse(bTime, Parser);
如果计算差值时需要考虑夏令时(DST)等,解析后转换时间:
ZoneId timeZone = ZoneId.systemDefault();
ZonedDateTime a = LocalDateTime.parse(aTime, Parser).atZone(timeZone);
ZonedDateTime b = LocalDateTime.parse(bTime, Parser).atZone(timeZone);
请仔细考虑用于转换的时区,以确保您获得预期的结果。
(3) null
的 ChronoUnit
将不起作用。 我不知道你想要哪个,所以这个选项是随机挑选:
ChronoUnit unit = ChronoUnit.DAYS;
通过这三项更改,您的方法在我的计算机上执行得很好。在一次运行中它打印出:
2016-06-28 22:29:44.700228
365
在同一次运行中,它返回了一个字符串 365
。
关于java - 无法将字符串转换为 ZonedDateTime : DateTimeParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44487065/