user1339295
user1339295

Reputation: 1

Convert UTC millisecond to UTC date in java

I am working in application where facing issue with time zones.

Want to convert UTC millisecond to UTC date object.

I already tried

   TimeZone utcZone = TimeZone.getTimeZone("UTC");    
   Calendar date = getInstance(utcZone);  
   date.setTimeInMillis(utcMillisecond);  
   date.getTime();

date.getTime is still returning my local time zone that is EST. I know that millisecond that I am getting from UI is in UTC millisecond.

Upvotes: 0

Views: 2089

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 340118

The old class java.util.Calendar silently applied your JVM’s current default time zone. You assumed it would be in UTC but it is not.

java.time

You are using old troublesome date-time classes that have been supplanted by the java.time framework in Java 8 and later.

I assume that by "UTC millisecond" you mean a count of milliseconds since the first moment of 1970 in UTC, 1970-01-01T00:00:00Z. That can be used directly to create a java.time.Instant, a moment on the timeline in UTC.

By the way be aware that java.time has nanosecond resolution, much finer than milliseconds.

Instant instant = Instant.ofEpochMilli( yourMillisNumber );

Call toString to generate a String as a textual representation of the date-time value in a format compliant with the ISO 8601 standard. For example:

2016-01-23T12:34:56.789Z

Upvotes: 1

Related Questions