【发布时间】:2018-04-20 06:34:23
【问题描述】:
问题
给定一个开始和结束时间戳以及一个持续时间,我想以持续时间为步长迭代该时间间隔。持续时间应以ISO 8601 表示法指定。应根据时区考虑夏令时。
示例代码:
// start/end at switch from summer to winter time
ZonedDateTime startTimestamp = ZonedDateTime.of( LocalDateTime.of(2018, 10, 28, 0, 0), ZoneId.of("CET"));
ZonedDateTime endTimestamp = startTimestamp.plusHours(5);
Duration duration = Duration.parse( "PT1H");
while( startTimestamp.isBefore(endTimestamp)) {
System.out.println( startTimestamp);
startTimestamp = startTimestamp.plus( duration);
}
结果:
2018-10-28T00:00+02:00[CET]
2018-10-28T01:00+02:00[CET]
2018-10-28T02:00+02:00[CET]
2018-10-28T02:00+01:00[CET]
2018-10-28T03:00+01:00[CET]
问题在于,只要持续时间最长为天,它就可以工作。来自 Duration 解析器文档:
然后有四个部分,每个部分由一个数字和一个后缀组成。这些部分具有“D”、“H”、“M”和“S”的 ASCII 后缀,表示天、小时、分钟和秒,接受大小写。
但ISO 8601 标准指定持续时间也可能以月和年为单位。
持续时间定义了时间间隔中的干预时间量,并且 由格式 P[n]Y[n]M[n]DT[n]H[n]M[n]S 或 P[n]W
表示
问题
考虑到周、月、年的日历元素,您如何在 ISO 8601 持续时间步骤中正确迭代 ZonedDateTime 间隔?
月份示例:
Start: 01.01.2018
End: 01.01.2019
我想每个月的第一天。将P1M 指定为持续时间当然会引发此异常:
Exception in thread "main" java.time.format.DateTimeParseException:
Text cannot be parsed to a Duration
【问题讨论】:
标签: java datetime java-8 java-time