【问题标题】:How to calculate remaining time between dates with daylight saving end date如何计算具有夏令时结束日期的日期之间的剩余时间
【发布时间】:2018-02-28 08:48:08
【问题描述】:

我有以下日期:

开始:2017-09-11T00:00:00+01:00 结束:2017-11-13T00:00:00+01:00

由于夏令时,用开始数据减去结束数据的毫秒数不是我的时区(欧洲/布鲁塞尔)的正确结果。 10 月 29 日晚上,时钟将拨回 1 小时。

我们应该如何在 Java/Android 中处理这个问题?

我尝试过使用 Joda Time,但无济于事。休息一小时。

【问题讨论】:

  • 你读过here吗?

标签: java android


【解决方案1】:

Java8 中,您将使用ZonedDateTime。这是official api docs

还有一个适用于您的案例的工作示例:

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));

产生:

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

更新:

对于基于Joda time 的预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());

产生:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2022-09-26
相关资源
最近更新 更多