Time Zone Handling
Part of the Logic & Flow section of Coddy's Java journey — lesson 59 of 59.
ZonedDateTime in Java represents a date and time with a time zone. It's useful when working with different time zones or converting between them.
Create a time in a specific zone:
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));You can also convert a LocalDateTime to a ZonedDateTime using .atZone():
LocalDateTime local = LocalDateTime.of(2024, 3, 15, 10, 30);
ZonedDateTime tokyo = local.atZone(ZoneId.of("Asia/Tokyo"));.atZone() attaches a time zone to an existing local date-time, producing a ZonedDateTime.
Convert time between zones:
ZonedDateTime newYork = tokyo.withZoneSameInstant(ZoneId.of("America/New_York"));After executing the above code, newYork contains the same instant as tokyo but in New York's time zone:
2024-03-15T10:30-04:00[America/New_York]
// Example outputTo format a ZonedDateTime, use DateTimeFormatter. The pattern letter Z or xxx formats the UTC offset (e.g. +09:00), and VV formats the zone ID (e.g. Asia/Tokyo):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx");
String formatted = tokyo.format(formatter);
// Example: 2024-03-15 10:30 +09:00Challenge
EasyCreate a method named convertTime that takes four arguments:
- A String (
dateTimeStr) in format "yyyy-MM-dd HH:mm" - A String (
sourceZone) source time zone ID - A String (
targetZone) target time zone ID - A boolean (
showOffset) whether to include timezone offset in output
The method should:
- Parse the input datetime in the source timezone
- Convert it to the target timezone
- Return formatted information about both times
Return messages should be:
- If invalid datetime: return "Invalid datetime format"
- If invalid zone: return "Invalid time zone"
- If showOffset is true: include offset in output
- Format: "Source: [time1], Target: [time2]"
Cheat sheet
ZonedDateTime represents a date and time with a time zone, useful for working with different time zones.
Create a time in a specific zone:
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));Convert a LocalDateTime to a ZonedDateTime using .atZone():
LocalDateTime local = LocalDateTime.now();
ZonedDateTime zoned = local.atZone(ZoneId.of("Asia/Tokyo"));Convert time between zones:
ZonedDateTime newYork = tokyo.withZoneSameInstant(ZoneId.of("America/New_York"));Format a ZonedDateTime including the UTC offset using Z or xxx patterns:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx");
String formatted = zoned.format(formatter);
// Example: 2024-03-15 10:30 +09:00Try it yourself
import java.util.Scanner;
import java.time.*;
import java.time.format.*;
public class Main {
public static String convertTime(String dateTimeStr, String sourceZone,
String targetZone, boolean showOffset) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String dateTimeStr = scanner.nextLine();
String sourceZone = scanner.nextLine();
String targetZone = scanner.nextLine();
boolean showOffset = Boolean.parseBoolean(scanner.nextLine());
System.out.println(convertTime(dateTimeStr, sourceZone, targetZone, showOffset));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet10Date and Time
LocalDate BasicsLocalTime OperationsLocalDateTime UsagePeriod and DurationDate FormattingTime Zone Handling2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap