How to I convert long (currentTimeInMillis) to UTC

2020-06-22 03:21发布

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

4条回答
女痞
2楼-- · 2020-06-22 03:51

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
查看更多
Anthone
3楼-- · 2020-06-22 03:59
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));
查看更多
淡お忘
4楼-- · 2020-06-22 03:59

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

查看更多
萌系小妹纸
5楼-- · 2020-06-22 04:06

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".

查看更多
登录 后发表回答