The Convert DateTime between timezones in Java 8 tutorial shows you how to convert a date and time between different time zones.
Other interesting posts you may like
Convert DateTime to ZonedDateTime
Here is a way to convert DateTime to ZonedDateTime with a specific timezone
1 2 3 4 5 |
String DATE_FORMAT = "dd-MM-yyyy hh:mm:ss a"; String dateInString = "03-11-2016 10:15:55 AM"; LocalDateTime ldt = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT)); ZoneId bangkokZoneId = ZoneId.of("Asia/Bangkok"); ZonedDateTime asiaZonedDateTime = ldt.atZone(bangkokZoneId); |
Convert ZonedDateTime to Date string
Below is a way to convert ZonedDateTime to Date string
1 2 3 |
String DATE_FORMAT = "dd-MM-yyyy hh:mm:ss a"; DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT); String dateinString = format.format(asiaZonedDateTime); |
Create a program to convert DateTime between timezones in Java 8
We will convert the datetime from timezone
1 2 |
(UTC+7:00) Asia/Singapore - Thailand Time Date (Bangkok) : 03-11-2016 09:35:55 AM |
to
1 2 |
(UTC-5:00) America/New_York - Eastern Standard Time Date (New York) : 02-11-2016 10:35:55 PM |
Noticed that when we are using time zone, avoid both java.util.Date and java.util.Calendar
Here is a main class to convert DateTime between timezones in Java 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.javabycode.date; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ConvertDateTimeToTimezones { private static final String DATE_FORMAT = "dd-MM-yyyy hh:mm:ss a"; public static void main(String[] args) { String dateInString = "03-11-2016 10:15:55 AM"; LocalDateTime ldt = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT)); ZoneId bangkokZoneId = ZoneId.of("Asia/Bangkok"); System.out.println("TimeZone : " + bangkokZoneId); //Note: LocalDateTime + ZoneId = ZonedDateTime ZonedDateTime asiaZonedDateTime = ldt.atZone(bangkokZoneId); System.out.println("Date (Bangkok) : " + asiaZonedDateTime); ZoneId newYokZoneId = ZoneId.of("America/New_York"); System.out.println("TimeZone : " + newYokZoneId); ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId); System.out.println("Date (New York) : " + nyDateTime); DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT); System.out.println("---DateTimeFormatter---"); System.out.println("Date (Bangkok) : " + format.format(asiaZonedDateTime)); System.out.println("Date (New York) : " + format.format(nyDateTime)); } } |
Run above main class and produce the output like below
That’s it on the tutorial Convert DateTime between timezones in Java 8.
References
ZonedDateTime Javadoc
Date JavaDoc
SimpledateFormat JavaDoc