Kotlin 程序:获取当前日期/时间
示例1:获取默认格式的当前日期和时间
import java.time.LocalDateTime
fun main(args: Array<String>) {
val current = LocalDateTime.now()
println("当前日期和时间是:$current")
}
当您运行该程序时,输出将为:
当前日期和时 间是:2017-08-02T11:25:44.973
在上述程序中,使用LocalDateTime.now()
方法将当前日期和时间存储在变量current
中。
对于默认格式,它只是从LocalDateTime
对象转换为字符串,使用toString()
方法。
示例2:使用模式获取当前日期和时间
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)
println("当前日期和时间是:$formatted")
}
当您运行该程序时,输出将为:
当前日期和时间是:2017-08-02 11:29:57.401
在上述程序中,我们使用DateTimeFormatter
对象定义了格式为Year-Month-Day Hours:Minutes:Seconds.Milliseconds
的模式。
然后,我们使用LocalDateTime
的format()
方法来使用给定的formatter
。这将得到格式化的字符串输出。
示例3:使用预定义常量获取当前日期时间
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.BASIC_ISO_DATE
val formatted = current.format(formatter)
println("当前日期是:$formatted")
}
当您运行该程序时,输出将为:
当前日期是:20170802
在上述程序中,我们使用预定义的格式常量BASIC_ISO_DATE
来获取当前ISO日期作为输出。
示例4:以本地化样式获取当前日期时间
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
val formatted = current.format(formatter)
println("当前日期是:$formatted")
}
当您运行该程序时,输出将为:
当前日期是:Aug 2, 2017 11:44:19 AM
在上述程序中,我们使用本地化样式Medium
来以给定的格式获取当前日期时间。还有其他样式可用:Full
、Long
和Short
。
如果您感兴趣,这里是所有DateTimeFormatter模式的列表。
此外,这是等效的Java代码:Java程序:获取当前日期和时间。