7

Really simple question, but I can't find a simple explanation anywhere. I want to get the current time in milliseconds:

val current = System.currentTimeMillis()

and convert the result into a Date Time format such as 2017-02-11T15:16:38.437Z. This is for Scala, if the question was unclear.

ChazMcDingle
  • 635
  • 2
  • 10
  • 18
  • 2
    Possible duplicate of [How to convert Milliseconds to "X mins, x seconds" in Java?](http://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java) – Yuval Itzchakov Feb 13 '17 at 11:58
  • 2
    Scala doesn't have a custom `scala.time` library. It builds on that fact you can use `java.time`. I don't think you'll find anything built in that doesn't. You can always use an external dependency such as [nscala-time](https://github.com/nscala-time/nscala-time) – Yuval Itzchakov Feb 13 '17 at 12:05

1 Answers1

13

Well... you can use java time api for doing that,

First, you need to convert those epoch milli-seconds to date-time objects,

import java.time.format.DateTimeFormatter
import java.time.{Instant, ZoneId, ZonedDateTime} 

val timeInMillis = System.currentTimeMillis()
//timeInMillis: Long = 1486988060666

val instant = Instant.ofEpochMilli(timeInMillis)
//instant: java.time.Instant = 2017-02-13T12:14:20.666Z

val zonedDateTimeUtc = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"))
//zonedDateTimeUtc: java.time.ZonedDateTime = 2017-02-13T12:14:20.666Z[UTC]

val zonedDateTimeIst = ZonedDateTime.ofInstant(instant, ZoneId.of("Asia/Calcutta"))
//zonedDateTimeIst: java.time.ZonedDateTime = 2017-02-13T17:44:20.666+05:30[Asia/Calcutta]

Now, that you want to get a formatted string for these,

val dateTimeFormatter1 = DateTimeFormatter.ISO_OFFSET_DATE_TIME

val zonedDateTimeUtcString1 = dateTimeFormatter1.format(zonedDateTimeUtc)
//zonedDateTimeUtcString1: String = 2017-02-13T12:24:19.248Z

val zonedDateTimeIstString1 = dateTimeFormatter1.format(zonedDateTimeIst)
//zonedDateTimeIstString1: String = 2017-02-13T17:54:19.248+05:30

val dateTimeFormatter2 = DateTimeFormatter.ISO_ZONED_DATE_TIME

val zonedDateTimeUtcString2 = dateTimeFormatter2.format(zonedDateTimeUtc)
//zonedDateTimeUtcString2: String = 2017-02-13T12:20:11.813Z[UTC]

val zonedDateTimeIstString2 = dateTimeFormatter2.format(zonedDateTimeIst)
//zonedDateTimeIstString2: String = 2017-02-13T17:50:11.813+05:30[Asia/Calcutta]
Maashu
  • 305
  • 2
  • 10
sarveshseri
  • 13,738
  • 28
  • 47