1
真的很簡單的問題,但我無法在任何地方找到簡單的解釋。我想獲得當前時間以毫秒爲單位:將當前時間以毫秒爲單位轉換爲日期Scala中的時間格式
val current = System.currentTimeMillis()
並將結果轉換成日期時間格式,如2017-02-11T15:16:38.437Z
。 這是針對斯卡拉的,如果問題不清楚的話。
真的很簡單的問題,但我無法在任何地方找到簡單的解釋。我想獲得當前時間以毫秒爲單位:將當前時間以毫秒爲單位轉換爲日期Scala中的時間格式
val current = System.currentTimeMillis()
並將結果轉換成日期時間格式,如2017-02-11T15:16:38.437Z
。 這是針對斯卡拉的,如果問題不清楚的話。
嗯......你可以使用Java 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]
的[如何轉換毫秒到Java中的「X分鐘,x秒」?](可能的複製http://stackoverflow.com/questions/625433/how-到轉換-毫秒到X-分鐘-X-第二s-in-java) –
如果兩個問題都與相同的語言有關,那麼這將是重複的。 – DarthBinks911
Scala沒有自定義'scala.time'庫。它建立在你可以使用'java.time'的基礎上。我認爲你不會發現任何內置的東西。您始終可以使用外部依賴項,例如[nscala-time](https://github.com/nscala-time/nscala-time) –