简介
处理日期和时间是现代开发中最常见的任务之一。无论是事件记录、截止日期计算、日历显示,还是应用程序国际化,Kotlin开发者都需要知道如何正确处理时间数据。在本文中,我们将深入探讨如何使用自Java 8起可用且与Kotlin完全兼容的现代java.time API在Kotlin中处理日期和时间。您将了解关键类、格式化、解析、时区处理以及实用的代码示例,这些都将帮助您编写清晰可靠的代码。
处理日期和时间的主要类
在Kotlin中,与Java一样,处理日期和时间主要基于java.time包。该包旨在取代过时的java.util.Date和java.util.Calendar。它提供了不可变且线程安全的类。让我们来看看其中最重要的几个。
LocalDate — 不含时间的日期
LocalDate类表示一个日期(年、月、日),不包含时间和时区。它非常适合表示生日、节假日或事件日期。
import java.time.LocalDate
fun main() { // 当前日期 val today: LocalDate = LocalDate.now() println("今天: $today") // 输出: 2025-04-11
// 指定日期 val specificDate: LocalDate = LocalDate.of(2025, 12, 25) println("圣诞节: $specificDate")
// 添加天数 val nextWeek: LocalDate = today.plusDays(7) println("一周后: $nextWeek")}LocalTime — 不含日期的时间
如果您只需要时间(小时、分钟、秒、纳秒),请使用LocalTime。
import java.time.LocalTime
fun main() { val now: LocalTime = LocalTime.now() println("当前时间: $now")
val meetingTime: LocalTime = LocalTime.of(14, 30) println("会议时间: $meetingTime")
val oneHourLater: LocalTime = now.plusHours(1) println("一小时后: $oneHourLater")}LocalDateTime — 同时包含日期和时间
这是LocalDate和LocalTime的组合。它是存储不绑定时区的时间点最常用的类。
import java.time.LocalDateTime
fun main() { val currentDateTime: LocalDateTime = LocalDateTime.now() println("现在: $currentDateTime")
val newYear: LocalDateTime = LocalDateTime.of(2026, 1, 1, 0, 0) println("新年: $newYear")}ZonedDateTime 和 Instant — 处理时区
ZonedDateTime在LocalDateTime的基础上增加了时区信息(ZoneId)。Instant表示UTC时间(机器时间)中的一个时间点。
import java.time.ZonedDateTimeimport java.time.ZoneIdimport java.time.Instant
fun main() { // 指定时区的时间 val moscowTime: ZonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/Moscow")) println("莫斯科时间: $moscowTime")
// UTC当前时刻 val instant: Instant = Instant.now() println("UTC时间戳: $instant")}日期格式化与解析
要将日期转换为字符串(格式化)或将字符串转换为日期(解析),可以使用DateTimeFormatter类。它允许您指定任何模式。
将日期格式化为字符串
import java.time.LocalDateimport java.time.format.DateTimeFormatter
fun main() { val date = LocalDate.now() val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") val formattedDate: String = date.format(formatter) println("格式化后的日期: $formattedDate") // 输出: 11.04.2025
// 其他模式示例 val formatter2 = DateTimeFormat