我想评论里已经都有了,所以我只是总结一下。
(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) A ChronoUnit
of null
行不通。我不知道你想要哪一个,所以这个选项是随机选择的:
ChronoUnit unit = ChronoUnit.DAYS;
通过这三个更改,您的方法可以在我的计算机上很好地执行。一次运行就打印出:
2016-06-28 22:29:44.700228
365
在同一次运行中,它返回了一个字符串365
.