Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert current time in milliseconds to Date Time format in Scala

Tags:

scala

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.

like image 986
ChazMcDingle Avatar asked Feb 13 '17 11:02

ChazMcDingle


1 Answers

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]
like image 133
sarveshseri Avatar answered Oct 22 '22 17:10

sarveshseri