如何在 kotlin 编程中将毫秒转换为时间戳



如何在 Kotlin 中将毫秒转换为时间戳。

以毫秒为单位的时间:1575959745000格式日/月/年 HH:MM:ss

编辑:现在,有 Kotlinx-datetime 库


目前没有对日期的纯粹 Kotlin 支持,只有持续时间。 您必须依靠目标平台的设施进行日期/时间解析和格式化。

请注意,无论您的目标是什么平台,在不定义时区的情况下将毫秒纪元转换为格式化日期都没有意义。

如果您的目标是 JVM,则可以通过以下方式使用java.timeAPI:

// define once somewhere in order to reuse it
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
// JVM representation of a millisecond epoch absolute instant
val instant = Instant.ofEpochMilli(1575959745000L)
// Adding the timezone information to be able to format it (change accordingly)
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
println(formatter.format(date)) // 10/12/2019 06:35:45

如果你的目标是JavaScript,事情会变得更加棘手。您可以执行以下操作以使用某种默认时区和某种足够接近的格式(由区域设置"en-gb"定义(:

val date = Date(1575959745000)
println(date.toLocaleString("en-gb")) // 10/12/2019, 07:35:45

您可以通过以下方法根据用于Date.toLocaleString()的标准 JS API 指定时区。但我还没有深入研究细节。

至于本地人,我不知道。

最新更新