Java – Convert date and time between timezone
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
(UTC-5:00) America/New_York - Eastern Standard Time Date : 21-1-2015 09:15:55 PM
- If you are using JDK >= 8, use the new java.time.* framework.
- If you are using JDK java.time.* framework is inspired by this library)
1. ZonedDateTime
Always use this new Java 8 java.time.ZonedDateTime to represent a date and time containing time zone.
package com.mkyong.date; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ZonedDateTimeExample < private static final String DATE_FORMAT = "dd-M-yyyy hh:mm:ss a"; public static void main(String[] args) < String dateInString = "22-1-2015 10:15:55 AM"; LocalDateTime ldt = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT)); ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore"); System.out.println("TimeZone : " + singaporeZoneId); //LocalDateTime + ZoneId = ZonedDateTime ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId); System.out.println("Date (Singapore) : " + 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("\n---DateTimeFormatter---"); System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime)); System.out.println("Date (New York) : " + format.format(nyDateTime)); >>
TimeZone : Asia/Singapore Date (Singapore) : 2015-01-22T10:15:55+08:00[Asia/Singapore] TimeZone : America/New_York Date (New York) : 2015-01-21T21:15:55-05:00[America/New_York] ---DateTimeFormatter--- Date (Singapore) : 22-1-2015 10:15:55 AM Date (New York) : 21-1-2015 09:15:55 PM
Note
Refer to this ZonedDateTime tutorial for more time zone, custom offset and daylight saving time (DST) examples.
2. Date
Note
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);
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)); >>
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
3. Calendar
3.1 A Calendar example to set a time zone :
Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setTimeZone(tzInAmerica);
A super common mistake is to get the java.util.Date directly like this :
//Wrong, it will display 22-1-2015 10:15:55 AM, time is still in the system default time zone! Date dateInAmerican = calendar.getTime());
In the above example, no matter what time zone you set in the Calendar, the Date object will be always printed with the default system time zone. (Check the Date.toString() source code)
3.2 The correct way should be using the DateFormat to format it :
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a"); TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York"); sdfAmerica.setTimeZone(tzInAmerica); sdfAmerica.format(calendar.getTime())
or get the Date via calendar.get() :
int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11 int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR); // 12 hour clock int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int ampm = calendar.get(Calendar.AM_PM); //0 = AM , 1 = PM
package com.mkyong.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; public class CalendarExample < 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); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setTimeZone(tzInAmerica); System.out.println("\nTimeZone : " + tzInAmerica.getID() + " - " + tzInAmerica.getDisplayName()); System.out.println("TimeZone : " + tzInAmerica); //Wrong! It will print the date with the system default time zone System.out.println("Date (New York) (Wrong!): " + calendar.getTime()); //Correct! need formatter System.out.println("Date (New York) (Correct!) : " + sdfAmerica.format(calendar.getTime())); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11 int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR); // 12 hour clock int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); int ampm = calendar.get(Calendar.AM_PM); //0 = AM , 1 = PM //Correct System.out.println("\nyear \t\t: " + year); System.out.println("month \t\t: " + month + 1); System.out.println("dayOfMonth \t: " + dayOfMonth); System.out.println("hour \t\t: " + hour); System.out.println("minute \t\t: " + minute); System.out.println("second \t\t: " + second); System.out.println("ampm \t\t: " + ampm); >>
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) (Wrong!): Thu Jan 22 10:15:55 MYT 2015 Date (New York) (Correct!) : 21-1-2015 09:15:55 PM year : 2015 month : 01 dayOfMonth : 21 hour : 9 minute : 15 second : 55 ampm : 1
4. Joda Time
4.1 A Joda Time example to set a time zone :
DateTime dt = new DateTime(date); DateTimeZone dtZone = DateTimeZone.forID("America/New_York"); DateTime dtus = dt.withZone(dtZone);
Again, a common mistake is getting the Date directly like this, time zone will be lost.
//Output : 22-1-2015 10:15:55 AM Date dateInAmerica = dtus.toDate();
The correct way is converted to Joda LocalDateTime first.
//Output : 21-1-2015 09:15:55 PM Date dateInAmerica = dtus.toLocalDateTime().toDate();
package com.mkyong.date; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class JodaTimeExample < 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); DateTime dt = new DateTime(date); DateTimeZone dtZone = DateTimeZone.forID("America/New_York"); DateTime dtus = dt.withZone(dtZone); TimeZone tzInAmerica = dtZone.toTimeZone(); Date dateInAmerica = dtus.toLocalDateTime().toDate(); //Convert to LocalDateTime first sdfAmerica.setTimeZone(tzInAmerica); System.out.println("\nTimeZone : " + tzInAmerica.getID() + " - " + tzInAmerica.getDisplayName()); System.out.println("TimeZone : " + tzInAmerica); System.out.println("DateTimeZone : " + dtZone); System.out.println("DateTime : " + dtus); System.out.println("dateInAmerica (Formatter) : " + formatter.format(dateInAmerica)); System.out.println("dateInAmerica (Object) : " + dateInAmerica); >>
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". ] DateTimeZone : America/New_York DateTime : 2015-01-21T21:15:55.000-05:00 dateInAmerica (Formatter) : 21-1-2015 09:15:55 PM dateInAmerica (Object) : Wed Jan 21 21:15:55 MYT 2015
P.S Tested with Joda-time 2.9.4
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Set the Time Zone of a Date in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this quick tutorial, we’ll see how to set the time zone of a date using Java 7, Java 8 and the Joda-Time library.
2. Using Java 8
Java 8 introduced a new Date-Time API for working with dates and times which was largely based off of the Joda-Time library.
The Instant class from Java Date Time API models a single instantaneous point on the timeline in UTC. This represents the count of nanoseconds since the epoch of the first moment of 1970 UTC.
First, we’ll obtain the current Instant from the system clock and ZoneId for a time zone name:
Instant nowUtc = Instant.now(); ZoneId asiaSingapore = ZoneId.of("Asia/Singapore");
Finally, the ZoneId and Instant can be utilized to create a date-time object with time-zone details. The ZonedDateTime class represents a date-time with a time-zone in the ISO-8601 calendar system:
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
We’ve used Java 8’s ZonedDateTime to represent a date-time with a time zone.
3. Using Java 7
In Java 7, setting the time-zone is a bit tricky. The Date class (which represents a specific instant in time) doesn’t contain any time zone information.
First, let’s get the current UTC date and a TimeZone object:
Date nowUtc = new Date(); TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
In Java 7, we need to use the Calendar class to represent a date with a time zone.
Finally, we can create a nowUtc Calendar with the asiaSingapore TimeZone and set the time:
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); nowAsiaSingapore.setTime(nowUtc);
It’s recommended to avoid the Java 7 date time API in favor of Java 8 date time API or the Joda-Time library.
4. Using Joda-Time
If Java 8 isn’t an option, we can still get the same kind of result from Joda-Time, a de-facto standard for date-time operations in the pre-Java 8 world.
First, we need to add the Joda-Time dependency to pom.xml:
To represent an exact point on the timeline we can use Instant from org.joda.time package. Internally, the class holds one piece of data, the instant as milliseconds from the Java epoch of 1970-01-01T00:00:00Z:
Instant nowUtc = Instant.now();
We’ll use DateTimeZone to represent a time-zone (for the specified time zone id):
DateTimeZone asiaSingapore = DateTimeZone.forID("Asia/Singapore");
Now the nowUtc time will be converted to a DateTime object using the time zone information:
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
This is how Joda-time API can be used to combine date and time zone information.
5. Conclusion
In this article, we found out how to set the time zone in Java using Java 7, 8 and Joda-Time API. To learn more about Java 8’s date-time support check out our Java 8 date-time intro.
As always the code snippet is available in the GitHub repository.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: