kotlin 怎么将yyyy-MM-dd HH:mm:ss格式的LocalDateTime转换为毫秒时间戳
可以通过以下代码将 yyyy-MM-dd HH:mm:ss 格式的 LocalDateTime 转换为毫秒时间戳:
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main() {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val dateTimeString = "2022-01-01 00:00:00"
val localDateTime = LocalDateTime.parse(dateTimeString, formatter)
val timestamp = localDateTime.toInstant(java.time.ZoneOffset.UTC).toEpochMilli()
println(timestamp)
}
在上面的代码中,我们首先使用 DateTimeFormatter 定义了 LocalDateTime 的格式。接着,我们将 yyyy-MM-dd HH:mm:ss 格式的日期字符串解析为 LocalDateTime 对象。然后,我们使用 toInstant 方法将 LocalDateTime 转换为 Instant 对象,并指定了时区为 UTC。最后,使用 toEpochMilli 方法将 Instant 对象转换为毫秒时间戳。
kotlin 毫秒时间戳怎么转换为yyyy-MM-dd HH:mm:ss格式的LocalDateTime
可以使用DateTimeFormatter
将LocalDateTime
格式化为指定的字符串格式。以下是示例代码:
val timestamp = 1617620873000 // 毫秒时间戳
val instant = Instant.ofEpochMilli(timestamp)
val zoneId = ZoneId.systemDefault()
val localDateTime = LocalDateTime.ofInstant(instant, zoneId)
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedDateTime = localDateTime.format(formatter)
首先,使用时间戳创建一个Instant
对象。然后,使用ZoneId.systemDefault()
获取本地时区的ZoneId
。接下来,使用LocalDateTime.ofInstant()
将Instant
对象转换为LocalDateTime
。然后,创建一个DateTimeFormatter
对象,指定要输出的日期时间格式。最后,使用LocalDateTime.format()
方法将LocalDateTime
格式化为指定格式的字符串。
kotlin中获取yyyy-MM-dd HH:mm:ss格式的当前时间
在Kotlin中,你可以使用java.time
包中的LocalDateTime
类来获取当前时间,并使用DateTimeFormatter
类来格式化时间。
首先,确保你的项目已经导入了java.time
包。在Kotlin中,你可以使用以下代码获取当前时间并格式化为"yyyy-MM-dd HH:mm:ss"格式:
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun getCurrentDateTime(): String {
val currentDateTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
return currentDateTime.format(formatter)
}
fun main() {
val currentDateTime = getCurrentDateTime()
println(currentDateTime)
}
这段代码定义了一个名为getCurrentDateTime
的函数,它使用LocalDateTime.now()
获取当前时间,然后使用DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
创建一个格式化器,最后使用currentDateTime.format(formatter)
将当前时间格式化为指定的格式。
在main
函数中,你可以调用getCurrentDateTime
函数来获取当前时间并打印输出。
运行这段代码,你将会得到当前时间的"yyyy-MM-dd HH:mm:ss"格式输出。
相关推荐

















