6

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

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • possible duplicate of [Convert timestamp to UTC timezone](http://stackoverflow.com/questions/17431402/convert-timestamp-to-utc-timezone) – childofsoong Aug 31 '15 at 23:16

4 Answers4

11

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

Bilk
  • 418
  • 6
  • 19
1
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));
Xirema
  • 19,889
  • 4
  • 32
  • 68
  • Given that the OP **specifically** says they are using Java 8 why are you recommending an absolutely ancient API?? – Boris the Spider Aug 31 '15 at 22:17
  • 2
    You can propose your own solution if you think you have a better one. – Xirema Aug 31 '15 at 22:18
  • 2
    @BoristheSpider: Last I heard, the Date class (and the Calendar class) had not been deprecated. In my opinion, there are some problems that are solved no less elegantly with the earlier classes ... and if you're aware of their limitations then there really isn't a problem. – scottb Aug 31 '15 at 23:14
1

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
Binzi Cao
  • 1,075
  • 5
  • 14
0

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

daydreamer
  • 87,243
  • 191
  • 450
  • 722