简体   繁体   English

如何计算夏令时结束日期之间的剩余时间

[英]How to calculate remaining time between dates with daylight saving end date

I have following dates: 我有以下日期:

Start: 2017-09-11T00:00:00+01:00 End: 2017-11-13T00:00:00+01:00 开始时间:2017-09-11T00:00:00 + 01:00结束时间:2017-11-13T00:00:00 + 01:00

Subtracting the milliseconds of the end data with start data is not the correct result for my timezone (Europe/Brussels) because of the daylight savings. 使用起始数据减去最终数据的毫秒数不是我的时区(欧洲/布鲁塞尔)的正确结果,因为夏令时。 On the 29th of October the clock will get set back 1 hour at night. 10月29日,时钟将在晚上1小时后退。

How should we handle this in Java/Android? 我们应该如何在Java / Android中处理这个问题?

I've tried using Joda Time but to no avail. 我尝试过使用Joda Time但无济于事。 It's one hour off. 这是一个小时的休息时间。

In Java8 , you would use ZonedDateTime . Java8 ,您将使用ZonedDateTime Here is the official api docs . 这是官方api文档

And a working example for your case: 并为您的案例提供一个工作示例:

DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;

// Start: 2017-09-11T00:00:00+02:00
LocalDateTime localDateTimeStart = LocalDateTime.of(2017, Month.SEPTEMBER, 11, 0, 0, 0);
// End: 2017-11-13T00:00:00+01:00 (instead of +02:00)
LocalDateTime localDateTimeEnd = LocalDateTime.of(2017, Month.NOVEMBER, 13, 0, 0, 0);

ZonedDateTime zonedDateTimeStart = localDateTimeStart.atZone(ZoneId.of("Europe/Brussels"));
System.out.println("ZonedDateTimeStart: " + formatter.format(zonedDateTimeStart));

ZonedDateTime zonedDateTimeEnd = localDateTimeEnd.atZone(ZoneId.of("Europe/Brussels"));
System.out.println("ZonedDateTimeEnd: " + formatter.format(zonedDateTimeEnd));

System.out.println("Remaining time in hours: " + ChronoUnit.HOURS.between(zonedDateTimeStart, zonedDateTimeEnd));

which produces: 产生:

ZonedDateTimeStart: 2017-09-11T00:00:00+02:00[Europe/Brussels]
ZonedDateTimeEnd: 2017-11-13T00:00:00+01:00[Europe/Brussels]
Remaining time in hours: 1513

UPDATE: 更新:

For a pre- java8 solution, based on Joda time , use this: 对于基于Joda time的pre- java8解决方案,请使用:

org.joda.time.DateTimeZone yourTimeZone = org.joda.time.DateTimeZone.forID("Europe/Brussels");
org.joda.time.DateTime start = new org.joda.time.DateTime(2017, 9, 11, 0, 0, 0, yourTimeZone);
org.joda.time.DateTime end = new org.joda.time.DateTime(2017, 11, 13, 0, 0, 0, yourTimeZone);
org.joda.time.Duration durationInHours = new org.joda.time.Duration(start, end);
System.out.println("ZonedDateTimeStart: " + start);
System.out.println("ZonedDateTimeEnd: " + end);
System.out.println("Remaining time in hours: " + durationInHours.toStandardHours().getHours());

which produces: 产生:

ZonedDateTimeStart: 2017-09-11T00:00:00.000+02:00
ZonedDateTimeEnd: 2017-11-13T00:00:00.000+01:00
Remaining time in hours: 1513

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM