ZoneOffset class

ZoneOffset represents a fixed offset from the UTC/Greenwich time (e.g., +05:30, -08:00). Unlike ZoneId, which includes daylight saving rules, ZoneOffset is a constant offset used by classes like OffsetDateTime and ZonedDateTime.

Commonly Used Methods

Simple Program

import java.time.ZoneOffset;

public class ZoneOffsetExample {
    public static void main(String[] args) {
        ZoneOffset offset1 = ZoneOffset.of("+05:30");
        ZoneOffset offset2 = ZoneOffset.ofHours(-4);

        System.out.println("Offset1: " + offset1);
        System.out.println("Offset2: " + offset2);
        System.out.println("Offset1 in seconds: " + offset1.getTotalSeconds());
    }
}

Problem Statement

LotusJavaPrince and Mahesh are creating a world clock dashboard. Each time zone is stored as a ZoneOffset so they can consistently calculate and display times in various regions without ambiguity.

They want to:

  • Create different ZoneOffset objects for major cities.
  • Display the total offset in seconds.
  • Verify their equality and generate offset strings.
import java.time.ZoneOffset;

public class WorldClockOffset {
    public static void main(String[] args) {
        System.out.println("World Clock Offset Dashboard - by LotusJavaPrince & Mahesh");

        // Step 1: Define time zone offsets
        ZoneOffset indiaOffset = ZoneOffset.of("+05:30");
        ZoneOffset nyOffset = ZoneOffset.ofHours(-4);
        ZoneOffset londonOffset = ZoneOffset.of("Z"); // Z == UTC

        // Step 2: Display offsets and their seconds
        System.out.println("India Offset: " + indiaOffset + " | Seconds: " + indiaOffset.getTotalSeconds());
        System.out.println("New York Offset: " + nyOffset + " | Seconds: " + nyOffset.getTotalSeconds());
        System.out.println("London Offset (UTC): " + londonOffset + " | Seconds: " + londonOffset.getTotalSeconds());

        // Step 3: Compare offsets
        boolean isSameOffset = indiaOffset.equals(nyOffset);
        System.out.println("Are India and New York Offsets Equal? " + isSameOffset);
    }
}
/*
World Clock Offset Dashboard - by LotusJavaPrince & Mahesh
India Offset: +05:30 | Seconds: 19800
New York Offset: -04:00 | Seconds: -14400
London Offset (UTC): Z | Seconds: 0
Are India and New York Offsets Equal? false
*/

The ZoneOffset class is a precise and efficient way to represent fixed offsets from UTC. It’s especially useful when:

  • You don’t need daylight saving or time zone rules (use ZoneId for that).
  • You need exact time offset calculations.
  • You’re building applications like loggers, schedulers, or converters.
Scroll to Top