示例 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()
方法存储在变量 current 中。
对于默认格式,它只需使用 toString()
方法从 LocalDateTime
对象转换为字符串。
我们也可以在Kotlin中使用 LocalDateTime
来加上或减去一定的时间量,例如,
要获取“现在”的准确日期 60 秒后,或者减去 60 秒,您可以使用:
LocalDateTime.now().plusSeconds(60) // adds 60 seconds from now on
LocalDateTime.now().minusSeconds(60) // subtract 60 seconds from now on
示例 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
对象定义了格式模式 年-月-日 时:分:秒.毫秒
。
然后,我们使用 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("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
来以给定的格式获取当前日期时间。还有其他样式:Full
、Long
和 Short
。
如果您有兴趣,这里是所有 DateTimeFormatter 模式的列表。
此外,这是等效的 Java 代码:Java 程序获取当前日期和时间