In this tutorial, we will show you few examples (ZonedDateTime (Java 8), Date, Calendar and Joda Time) to convert a date and time between different time zones.
All examples will be converting the date and time from
(UTC+8:00) Asia/Singapore - Singapore Time
Date : 22-1-2015 10:15:55 AM
to
(UTC-5:00) America/New_York - Eastern Standard Time
Date : 21-1-2015 09:15:55 PM
2. Date
Note
The
The
java.util.Date
has no concept of time zone, and only represents the number of seconds passed since the Unix epoch time – 1970-01-01T00:00:00Z. But, if you print the Date object directly, the Date object will be always printed with the default system time zone. Check the
Date.toString()
source code.
2.1 Set a time zone to DateFormat
and format the java.util.Date
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String sDateInAmerica = sdfAmerica.format(date);
2.2 Full example
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateExample {
private static final String DATE_FORMAT = "dd-M-yyyy hh:mm:ss a";
public static void main(String[] args) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String dateInString = "22-01-2015 10:15:55 AM";
Date date = formatter.parse(dateInString);
TimeZone tz = TimeZone.getDefault();
// From TimeZone Asia/Singapore
System.out.println("TimeZone : " + tz.getID() + " - " + tz.getDisplayName());
System.out.println("TimeZone : " + tz);
System.out.println("Date (Singapore) : " + formatter.format(date));
// To TimeZone America/New_York
SimpleDateFormat sdfAmerica = new SimpleDateFormat(DATE_FORMAT);
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
sdfAmerica.setTimeZone(tzInAmerica);
String sDateInAmerica = sdfAmerica.format(date); // Convert to String first
Date dateInAmerica = formatter.parse(sDateInAmerica); // Create a new Date object
System.out.println("\nTimeZone : " + tzInAmerica.getID() + " - " + tzInAmerica.getDisplayName());
System.out.println("TimeZone : " + tzInAmerica);
System.out.println("Date (New York) (String) : " + sDateInAmerica);
System.out.println("Date (New York) (Object) : " + formatter.format(dateInAmerica));
}
}
Output
TimeZone : Asia/Kuala_Lumpur - Malaysia Time
TimeZone : sun.util.calendar.ZoneInfo[id="Asia/Kuala_Lumpur",...]
Date (Singapore) : 22-1-2015 10:15:55 AM
TimeZone : America/New_York - Eastern Standard Time
TimeZone : sun.util.calendar.ZoneInfo[id="America/New_York",...]
Date (New York) (String) : 21-1-2015 09:15:55 PM
Date (New York) (Object) : 21-1-2015 09:15:55 PM