非常简单的问题,但我无法在任何地方找到简单的解释。我想以毫秒为单位获取当前时间:
val current = System.currentTimeMillis()
并将结果转换为日期时间格式,例如2017-02-11T15:16:38.437Z
。
如果问题不清楚,这适用于Scala。
答案 0 :(得分:6)
嗯......你可以使用java time api来做到这一点,
首先,您需要将这些纪元毫秒转换为日期时间对象
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]
现在,您想要获取这些格式化的字符串,
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 = dateTimeFormatter.format(zonedDateTimeUtc)
//zonedDateTimeUtcString2: String = 2017-02-13T12:20:11.813Z[UTC]
val zonedDateTimeIstString2 = dateTimeFormatter.format(zonedDateTimeIst)
//zonedDateTimeIstString2: String = 2017-02-13T17:50:11.813+05:30[Asia/Calcutta]