Sunday, August 14, 2016

Some useful use-cases of ZonedDateTime

In this example, you are going to see how to calculate the difference in hours between two time zones ("Asia/Singapore" and "Pacific/Auckland") in Java :

import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Duration;

public class TimeDifference {
public static void main(String[] args) {
ZoneId singaporeZone = ZoneId.of("Asia/Singapore");
ZonedDateTime dateTimeInSingapore = ZonedDateTime.of(LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0),
singaporeZone);

ZoneId aucklandZone = ZoneId.of("Pacific/Auckland");
ZonedDateTime sameDateTimeInAuckland = dateTimeInSingapore.withZoneSameInstant(aucklandZone);

Duration timeDifference = Duration.between(dateTimeInSingapore.toLocalTime(),
sameDateTimeInAuckland.toLocalTime());

System.out.printf("Time difference between %s and %s zones is %d hours", singaporeZone, aucklandZone,
timeDifference.toHours());
}
}

This code above results in:

Time difference between Asia/Singapore and Pacific/Auckland zones is 5 hours

Use-case 2:

import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FlightTravel {
public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy hh.mm a");

// Leaving on 1st Jan 2016, 6:00am from "Singapore"
ZonedDateTime departure = ZonedDateTime.of(LocalDateTime.of(2016, Month.JANUARY, 1, 6, 0),
ZoneId.of("Asia/Singapore"));

System.out.println("Departure: " + dateTimeFormatter.format(departure));

// Arrival on the same day in 10 hours in "Auckland"
ZonedDateTime arrival = departure.withZoneSameInstant(ZoneId.of("Pacific/Auckland")).plusHours(10);

System.out.println("Arrival: " + dateTimeFormatter.format(arrival));
}
}

This outputs the following :

Departure: 01 Jan 2016 06.00 AM
Arrival: 01 Jan 2016 09.00 PM

No comments:

Post a Comment