如何在 Kotlin 中获取当前本地日期和时间?
kotlin mobile developmentapps/applications
Kotlin 是一种统计类型语言,它基于 Java,因此所有 Java 代码都可以轻松地在 Kotlin 中编译。在本文中,我们将了解如何在 Kotlin 中生成当前本地日期和时间。
由于 Kotlin 与 Java 可互操作,我们将使用 Java 实用程序类和简单日期格式类来获取当前本地日期和时间。
示例 - 使用 SimpleDateFormat 获取当前日期和时间
import java.text.SimpleDateFormat
import java.util.*
fun main(args: Array<String>) {
val simpleDate = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = simpleDate.format(Date())
println(" 当前日期为:" +currentDate)
}
输出
执行后,将生成当前日期和时间。请注意,以下输出是服务器日期和时间,因此在您的系统上运行此代码时会有所不同。
当前日期为:28/2/2022 12:58:59
示例 –使用 LocalDateTime 获取当前日期和时间
还有一个类 "LocalDateTime" 可用于生成本地日期和时间。
import java.time.LocalDateTime
fun main(args: Array<String>) {
val current = LocalDateTime.now()
println("当前日期和时间为:$current")
}
输出
执行后,将产生以下输出 −
当前日期和时间为:2022-02-28T13:00:13.027

