How to I convert long (currentTimeInMillis) to UTC

2020-06-22 03:14发布

问题:

My client is sending me Long which could be thought as

scala> System.currentTimeMillis
res3: Long = 1441056836609

scala> 

How do I convert that into UTC timeStamp?

On Server, we are using Java 8

回答1:

You can use the Instant class methods.

import java.time.Instant;
import java.time.ZoneOffset;

Instant.ofEpochMilli(<yourmillis>).atOffset(ZoneOffset.UTC).toString();

Your example date would be "2015-08-31T21:33:56.609Z".



回答2:

Date dateFromTime = new Date(timeInMillis);

That will get a Date object, which you can then spit out in a proper UTC format using

DateFormat dateFormatter = SimpleDateFormat(/*UTC Format String*/, Locale./*Your Locale here*/);
System.out.printf("%s\n", dateFormatter.format(dateFromTime));


回答3:

Since you are using scala, I would suggest you use the scala way, nscala-time is a very good library

scala> import com.github.nscala_time.time.Imports._
import com.github.nscala_time.time.Imports._

scala> DateTimeZone.setDefault(DateTimeZone.UTC)

scala> new DateTime(1441056836609L)
res1: org.joda.time.DateTime = 2015-08-31T21:33:56.609Z


回答4:

This is what I am doing

I am using Joda-Time and doing

DateTimeZone.setDefault(DateTimeZone.UTC);
DateTime.now.toString

On client I see it as

Wed, 02 Sep 2015 20:57:34 GMT

and on server I see it as

2015-09-02T20:24:43.594Z

P.S. Don't compare values, they are copied differently, the format is what I wanted to share