将当前时间(以毫秒为单位)转换为 Scala 中的日期时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/42203276/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert current time in milliseconds to Date Time format in Scala
提问by ChazMcDingle
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.
并将结果转换为日期时间格式,例如2017-02-11T15:16:38.437Z. 如果问题不清楚,这是针对 Scala 的。
回答by Sarvesh Kumar Singh
Well... you can use java time api for doing that,
嗯...你可以使用 java time api 来做到这一点,
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]

