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