Menu
Coddy logo textTech

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 create a ZonedDateTime from a LocalDateTime using .atZone():

LocalDateTime localDT = LocalDateTime.of(2024, 3, 15, 10, 30);
ZonedDateTime tokyo = localDT.atZone(ZoneId.of("Asia/Tokyo"));

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 output

To format a ZonedDateTime, use DateTimeFormatter. You can include the timezone offset in the output using the pattern letter Z or XXX:

// Without offset
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

// With offset (e.g. +09:00 or -04:00)
DateTimeFormatter fmtWithOffset = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm XXX");

String result = newYork.format(fmtWithOffset);
// Example: 2024-03-15 10:30 -04:00
challenge icon

Challenge

Easy

Create a method named convertTime that takes four arguments:

  1. A String (dateTimeStr) in format "yyyy-MM-dd HH:mm"
  2. A String (sourceZone) source time zone ID
  3. A String (targetZone) target time zone ID
  4. A boolean (showOffset) whether to include timezone offset in output

The method should:

  1. Parse the input datetime in the source timezone
  2. Convert it to the target timezone
  3. 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]"

Try 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));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow