Converting Dates and Times Based on the Time Zone - Java Date Time

Java examples for Date Time:ZonedDateTime

Introduction

The following table lists the Time Zone Classes.

Class Name Description
ZoneId Specifies zone identifier and is used for conversions.
ZoneOffset Specifies a time zone offset from Greenwich/UTC time.
ZonedDateTime A date-time object that also handles the time zone data with time zone offset from Greenwich/UTC time.
ZoneRules Rules defining how a zone offset varies for a specified time zone.
ZoneRulesProvider Provider of time zone rules to a particular system.
ZoneOffsetTransitionTransition between two offsets by a discontinuity in the local timeline.
ZoneOffsetTransitionRuleRules expressing how to create a transition.

Demo Code

import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRules;

public class Main {

  public static void report(LocalDateTime checkOut,ZoneId checkOutZone, LocalDateTime checkIn, ZoneId checkInZone) {
    ZonedDateTime beginTrip = ZonedDateTime.of(checkOut, checkOutZone);
    System.out.println("Trip Begins: " + beginTrip);

    // Get the rules of the check out time zone
    ZoneRules checkOutZoneRules = checkOutZone.getRules();
    System.out.println("Checkout Time Zone Rules: " + checkOutZoneRules);

    // If the trip took 4 days
    ZonedDateTime beginPlus = beginTrip.plusDays(4);
    System.out.println("Four Days Later: " + beginPlus);

    // End of trip in starting time zone
    ZonedDateTime endTripOriginalZone = ZonedDateTime.of(checkIn, checkOutZone);
    ZonedDateTime endTrip = ZonedDateTime.of(checkIn, checkInZone);
    int diff = endTripOriginalZone.compareTo(endTrip);
    String diffStr = (diff >= 0) ? "NO" : "YES";

    System.out.println("End trip date/time in original zone: "+ endTripOriginalZone);
    System.out.println("End trip date/time in check-in zone: " + endTrip);
    System.out.println("Original Zone Time is less than new zone time? " + diffStr);

    ZoneId checkOutZoneId = beginTrip.getZone();
    ZoneOffset checkOutOffset = beginTrip.getOffset();
    ZoneId checkInZoneId = endTrip.getZone();
    ZoneOffset checkInOffset = endTrip.getOffset();

    System.out.println("Check out zone and offset: " + checkOutZoneId + checkOutOffset);
    System.out.println("Check in zone and offset: " + checkInZoneId + checkInOffset);

  }/*from  w  ww .j  av a  2 s.  co  m*/

  public static void main(String[] args) {
    LocalDateTime startRental = LocalDateTime.of(2015, Month.DECEMBER, 13, 13, 00);
    ZoneId startZone = ZoneId.of("US/Eastern");

    LocalDateTime endRental = LocalDateTime.of(2015, Month.DECEMBER, 18, 10, 00);
    ZoneId endZone = ZoneId.of("US/Mountain");
    report(startRental, startZone, endRental, endZone);
  }
}

Result


Related Tutorials