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:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>
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.