Skip to content

Latest commit

 

History

History
118 lines (73 loc) · 3.14 KB

File metadata and controls

118 lines (73 loc) · 3.14 KB

Kotlin 程序:获取当前日期/时间

原文: https://www.programiz.com/kotlin-programming/examples/current-date-time

在此程序中,您将学习在 Kotlin 中获取不同格式的当前日期和时间。

示例 1:以默认格式获取当前日期和时间

import java.time.LocalDateTime

fun main(args: Array<String>) {

    val current = LocalDateTime.now()

    println("Current Date and Time is: $current")
}

运行该程序时,输出为:

Current Date and Time is: 2017-08-02T11:25:44.973

在上述程序中,当前日期和时间使用LocalDateTime.now()方法以可变电流存储。

对于默认格式,只需使用toString()方法将其从LocalDateTime对象转换为字符串即可。


示例 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("Current Date and Time is: $formatted")
}

运行该程序时,输出为:

Current Date and Time is: 2017-08-02 11:29:57.401

在上面的程序中,我们使用DateTimeFormatter对象定义了Year-Month-Day Hours:Minutes:Seconds.Milliseconds格式的模式。

然后,我们使用了LocalDateTimeformat()方法来使用给定的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("Current Date is: $formatted")
}

运行该程序时,输出为:

Current Date is: 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("Current Date is: $formatted")
}

运行该程序时,输出为:

Current Date is: Aug 2, 2017 11:44:19 AM

在上面的程序中,我们使用了本地化样式Medium以给定的格式获取当前日期时间。 还有其他样式:FullLongShort


如果您有兴趣,这里是所有DateTimeFormatter模式的列表。

另外,这是等效的 Java 代码: Java 程序:获取当前日期和时间