Setting time zone of a java util Date

0 votes

Can someone help me in specifying the time zone of a date object that I have parsed from a String?
The timezone is not specified in the String but by default, it is setting the local time zone as the time zone of the date object.
 Please suggest.

Aug 14, 2018 in Java by 93.lynn
• 1,600 points
60,219 views

3 answers to this question.

0 votes

You can make use of the following DateFormat.

SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
myDate.setTimeZone(TimeZone.getTimeZone("UTC"));
Date newDate = myDate.parse("2010-05-23T09:01:02");

You need to do this because by default java.util.Date objects do not contain any timezone information.

answered Aug 14, 2018 by anto.trigg4
• 3,440 points
0 votes

Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.

As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.

answered Dec 15, 2020 by Roshni
• 10,440 points
That's a bit oversimplified. Date (at least in jdk8) contains a member cdate. If null you are right, but whenever that is set (and that is the case if the Date was obtained from a Calendar) then java.util.Date works as a date within a timezone. So you can "set the timezone of a Date" by getting a calendar of you desired timezone, initialize it with your given  Date's millis (getTime()) and then call getTime() on the Calendar: You get a Date with timezone information.
0 votes

Using Java 8

Java 8 introduced a new Date-Time API for working with dates and times which was largely based on 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 ZonedDat