sunder
sunder

Reputation: 1017

How to set Date object to point to different time zone in java

In the code below I have used calendar object to initialize time Zone to GMT and get the time accordingly but when I put back in date object, its automatically converting to my local time zone i.e. IST.

Calendar gmt = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dt=gmt.getTime();

Could anyone suggest a way through which I can retain the GMT format in date object also.

Upvotes: 0

Views: 1257

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338386

java.time

The other answers are correct. The toString method silently applies your JVM’s current default time zone. This is one of many poor design choices in the old date-time classes. Dump those old classes. Move on to the java.time framework built into Java 8 and later.

An Instant is a moment on the time line in UTC.

Instant now = Instant.now();

Apply a time zone (ZoneId) to an Instant to get a ZonedDateTime.

Why are we bothering to create a ZonedDateTime in UTC if the Instant is already in UTC? Because a ZonedDateTime gives you flexibility in formatting String representations of the date-time values. The java.time.format package does not work with Instant objects.

A subclass of ZoneId, ZoneOffset, has a constant for UTC.

ZonedDateTime zdtUtc = ZonedDateTime.ofInstant(  ZoneOffset.UTC );

Adjust into any desired time zone.

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = ZonedDateTime.ofInstant( instant , zoneId );

Use proper time zone names

Avoid using 3-4 letter codes for time zones. They are neither standardized nor unique. By IST did you mean India Standard Time or Irish Standard Time?

Use standard time zone names. Most are in the pattern of continent/region. For India, Asia/Kolkata. For Ireland, Europe/Dublin.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500165

its automatically converting to my local time zone i.e. IST

No it's not. A Date object doesn't have a time zone - it's just an instant in time.

You'll see the system-local time zone if you call toString() on a Date, because that's unfortunately what Date.toString() does... but the time zone is not part of the information stored in a Date.

If you want to see a textual representation of a Date in a particular time zone, use DateFormat and set the time zone that you want to use.

Upvotes: 2

Adriaan Koster
Adriaan Koster

Reputation: 16209

The Date class does not represent a timezone. It's toString method uses the default platform time zone to output a human readable timestamp, internally it's just a long.

Upvotes: 1

Related Questions