1

I have following dates:

Start: 2017-09-11T00:00:00+01:00 End: 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.

How should we handle this in Java/Android?

I've tried using Joda Time but to no avail. It's one hour off.

Sander Versluys
  • 72,737
  • 23
  • 84
  • 91
  • Have you read [here](https://stackoverflow.com/questions/10545960/how-to-tackle-daylight-savings-using-timezone-in-java)? – MatPag Sep 19 '17 at 14:23

1 Answers1

3

In Java8, you would use ZonedDateTime. Here is the official api docs.

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:

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
aUserHimself
  • 1,589
  • 2
  • 17
  • 26