How to I convert long (currentTimeInMillis) to UTC timestamp?

泄露秘密 提交于 2020-01-01 05:51:47

问题


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



来源:https://stackoverflow.com/questions/32320428/how-to-i-convert-long-currenttimeinmillis-to-utc-timestamp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!