Monday, June 5, 2017

Java 8 Date and Time API: How to Convert a Time Zone between Countries


In this tutorial, you will learn:
  • How to convert a time zone between different countries using the new Java 8 Date and Time API
Example
package com.melody.datetime;

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

public class ConvertTimezoneDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a");

  String dateAsString = "05/13/2017 07:30:45 AM";

  // Instantiate a LocalDateTime (without timezone)
  LocalDateTime localDateTime = LocalDateTime.parse(dateAsString, formatter);
  System.out.println("Local date & time without timezone: " + localDateTime.format(formatter));

  // Convert LocalDateTime to ZonedDateTime (timezone = Shanghai)
  ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
  ZonedDateTime shanghaiZonedDateTime = localDateTime.atZone(shanghaiZoneId);
  System.out.println("Date & time in Shanghai: " + shanghaiZonedDateTime.format(formatter)
     + " " + shanghaiZonedDateTime.getZone());

  // Convert ZonedDateTime to another timezone
  ZoneId newYorkZoneId = ZoneId.of("America/New_York");
  ZonedDateTime newYorkZonedDateTime = shanghaiZonedDateTime.withZoneSameInstant(newYorkZoneId);
  System.out.println("Date & time in New York: " + newYorkZonedDateTime.format(formatter)
    + " " + newYorkZonedDateTime.getZone());
 }
}
Output

Local date & time without timezone: 05/13/2017 07:30:45 AM
Date & time in Shanghai: 05/13/2017 07:30:45 AM Asia/Shanghai
Date & time in New York: 05/12/2017 07:30:45 PM America/New_York


No comments:

Post a Comment