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

对着背影说爱祢 提交于 2019-12-03 17:24:32

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

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));

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

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

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