7.Kotlin的日期类

以下是 Kotlin 中常用时间类(基于 java.time 包)的核心方法及使用示例,参考数组方法的表格形式,按类分类展示:

一、LocalDate(日期:年/月/日)

方法签名 返回值 说明 示例
now(): LocalDate LocalDate 获取当前日期 LocalDate.now() → 2023-10-05
of(year: Int, month: Int, day: Int): LocalDate LocalDate 创建指定日期 LocalDate.of(2023, 10, 5) → 2023-10-05
of(year: Int, month: Month, day: Int): LocalDate LocalDate 用Month枚举创建 LocalDate.of(2023, Month.OCTOBER, 5)
getYear(): Int Int 获取年份 LocalDate.now().getYear() → 2023
getMonth(): Month Month 获取月份(枚举) LocalDate.now().getMonth() → OCTOBER
getMonthValue(): Int Int 获取月份(数字1-12) LocalDate.now().getMonthValue() → 10
getDayOfMonth(): Int Int 获取当月第几天 LocalDate.now().getDayOfMonth() → 5
getDayOfWeek(): DayOfWeek DayOfWeek 获取星期几(枚举) LocalDate.now().getDayOfWeek() → THURSDAY
plusYears(years: Long): LocalDate LocalDate 增加年份 LocalDate.of(2023,10,5).plusYears(1) → 2024-10-05
plusMonths(months: Long): LocalDate LocalDate 增加月份 LocalDate.of(2023,10,5).plusMonths(1) → 2023-11-05
plusDays(days: Long): LocalDate LocalDate 增加天数 LocalDate.of(2023,10,5).plusDays(1) → 2023-10-06
minusYears(years: Long): LocalDate LocalDate 减少年份 LocalDate.of(2023,10,5).minusYears(1) → 2022-10-05
minusMonths(months: Long): LocalDate LocalDate 减少月份 LocalDate.of(2023,10,5).minusMonths(1) → 2023-09-05
minusDays(days: Long): LocalDate LocalDate 减少天数 LocalDate.of(2023,10,5).minusDays(1) → 2023-10-04
isAfter(other: LocalDate): Boolean Boolean 是否在指定日期之后 LocalDate.of(2023,10,6).isAfter(LocalDate.of(2023,10,5)) → true
isBefore(other: LocalDate): Boolean Boolean 是否在指定日期之前 LocalDate.of(2023,10,4).isBefore(LocalDate.of(2023,10,5)) → true
isEqual(other: LocalDate): Boolean Boolean 是否与指定日期相等 LocalDate.of(2023,10,5).isEqual(LocalDate.of(2023,10,5)) → true
atTime(time: LocalTime): LocalDateTime LocalDateTime 结合时间生成LocalDateTime LocalDate.now().atTime(12,30) → 2023-10-05T12:30
parse(text: CharSequence): LocalDate LocalDate 从字符串解析日期(默认格式yyyy-MM-dd) LocalDate.parse("2023-10-05") → 2023-10-05

二、LocalTime(时间:时/分/秒)

方法签名 返回值 说明 示例
now(): LocalTime LocalTime 获取当前时间 LocalTime.now() → 15:30:45.123
of(hour: Int, minute: Int): LocalTime LocalTime 创建指定时分 LocalTime.of(12, 30) → 12:30
of(hour: Int, minute: Int, second: Int): LocalTime LocalTime 创建指定时分秒 LocalTime.of(12,30,45) → 12:30:45
getHour(): Int Int 获取小时(0-23) LocalTime.now().getHour() → 15
getMinute(): Int Int 获取分钟(0-59) LocalTime.now().getMinute() → 30
getSecond(): Int Int 获取秒(0-59) LocalTime.now().getSecond() → 45
getNano(): Int Int 获取纳秒(0-999,999,999) LocalTime.now().getNano() → 123456789
plusHours(hours: Long): LocalTime LocalTime 增加小时 LocalTime.of(12,30).plusHours(1) → 13:30
plusMinutes(minutes: Long): LocalTime LocalTime 增加分钟 LocalTime.of(12,30).plusMinutes(30) → 13:00
plusSeconds(seconds: Long): LocalTime LocalTime 增加秒 LocalTime.of(12,30).plusSeconds(60) → 12:31
minusHours(hours: Long): LocalTime LocalTime 减少小时 LocalTime.of(12,30).minusHours(1) → 11:30
minusMinutes(minutes: Long): LocalTime LocalTime 减少分钟 LocalTime.of(12,30).minusMinutes(30) → 12:00
isAfter(other: LocalTime): Boolean Boolean 是否在指定时间之后 LocalTime.of(13,0).isAfter(LocalTime.of(12,30)) → true
isBefore(other: LocalTime): Boolean Boolean 是否在指定时间之前 LocalTime.of(12,0).isBefore(LocalTime.of(12,30)) → true
atDate(date: LocalDate): LocalDateTime LocalDateTime 结合日期生成LocalDateTime LocalTime.now().atDate(LocalDate.now()) → 2023-10-05T15:30:45
parse(text: CharSequence): LocalTime LocalTime 从字符串解析时间(默认格式HH:mm:ss) LocalTime.parse("12:30:45") → 12:30:45

三、LocalDateTime(日期+时间)

方法签名 返回值 说明 示例
now(): LocalDateTime LocalDateTime 获取当前日期时间 LocalDateTime.now() → 2023-10-05T15:30:45
of(date: LocalDate, time: LocalTime): LocalDateTime LocalDateTime 结合日期和时间 LocalDateTime.of(LocalDate.now(), LocalTime.now())
of(year: Int, month: Int, day: Int, hour: Int, minute: Int): LocalDateTime LocalDateTime 直接创建 LocalDateTime.of(2023,10,5,12,30) → 2023-10-05T12:30
toLocalDate(): LocalDate LocalDate 提取日期部分 LocalDateTime.now().toLocalDate() → 2023-10-05
toLocalTime(): LocalTime LocalTime 提取时间部分 LocalDateTime.now().toLocalTime() → 15:30:45
plusYears(years: Long): LocalDateTime LocalDateTime 增加年份 LocalDateTime.now().plusYears(1)
minusMonths(months: Long): LocalDateTime LocalDateTime 减少月份 LocalDateTime.now().minusMonths(1)
isAfter(other: LocalDateTime): Boolean Boolean 是否在指定日期时间之后 LocalDateTime.now().isAfter(LocalDateTime.now().minusHours(1)) → true
atZone(zone: ZoneId): ZonedDateTime ZonedDateTime 转换为带时区的时间 LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai"))

四、ZonedDateTime(带时区的日期时间)

方法签名 返回值 说明 示例
now(zone: ZoneId): ZonedDateTime ZonedDateTime 获取指定时区的当前时间 ZonedDateTime.now(ZoneId.of("UTC"))
now(): ZonedDateTime ZonedDateTime 获取系统默认时区的当前时间 ZonedDateTime.now() → 2023-10-05T15:30:45+08:00[Asia/Shanghai]
getZone(): ZoneId ZoneId 获取时区 ZonedDateTime.now().getZone() → Asia/Shanghai
withZoneSameInstant(zone: ZoneId): ZonedDateTime ZonedDateTime 转换到另一个时区(时间点不变) ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC"))
toLocalDateTime(): LocalDateTime LocalDateTime 转换为本地日期时间(无时区) ZonedDateTime.now().toLocalDateTime()
toInstant(): Instant Instant 转换为时间戳 ZonedDateTime.now().toInstant()

五、Instant(时间戳,UTC)

方法签名 返回值 说明 示例
now(): Instant Instant 获取当前UTC时间戳 Instant.now() → 2023-10-05T07:30:45.123Z
toEpochMilli(): Long Long 转换为毫秒级时间戳(1970年起) Instant.now().toEpochMilli() → 1696507845123
plusMillis(millis: Long): Instant Instant 增加毫秒 Instant.now().plusMillis(1000)
minusSeconds(seconds: Long): Instant Instant 减少秒 Instant.now().minusSeconds(60)
atZone(zone: ZoneId): ZonedDateTime ZonedDateTime 转换为指定时区的时间 Instant.now().atZone(ZoneId.of("Asia/Shanghai"))

六、Duration(时间间隔:时/分/秒)

方法签名 返回值 说明 示例
between(start: T, end: T): Duration Duration 计算两个时间的间隔 Duration.between(LocalTime.of(12,0), LocalTime.of(13,30)) → PT1H30M
ofHours(hours: Long): Duration Duration 创建指定小时的间隔 Duration.ofHours(2) → PT2H
plusMinutes(minutes: Long): Duration Duration 增加分钟 Duration.ofHours(1).plusMinutes(30) → PT1H30M
toMinutes(): Long Long 转换为总分钟数 Duration.ofHours(1).toMinutes() → 60
isNegative(): Boolean Boolean 是否为负间隔 Duration.ofHours(-1).isNegative() → true

七、Period(日期间隔:年/月/日)

方法签名 返回值 说明 示例
between(start: LocalDate, end: LocalDate): Period Period 计算两个日期的间隔 Period.between(LocalDate.of(2023,1,1), LocalDate.of(2023,10,5)) → P9M4D
ofYears(years: Int): Period Period 创建指定年数的间隔 Period.ofYears(1) → P1Y
plusMonths(months: Int): Period Period 增加月数 Period.ofYears(1).plusMonths(3) → P1Y3M
getDays(): Int Int 获取天数部分 Period.between(LocalDate.of(2023,10,1), LocalDate.of(2023,10,5)).getDays() → 4

综合示例

kotlin 复制代码
import java.time.*
import java.time.format.DateTimeFormatter

fun main() {
    // 1. 获取当前日期并加1天
    val tomorrow = LocalDate.now().plusDays(1)
    println("明天: $tomorrow")

    // 2. 解析字符串为日期并比较
    val deadline = LocalDate.parse("2023-12-31")
    println("是否过期: ${LocalDate.now().isAfter(deadline)}")

    // 3. 计算两个时间的间隔
    val start = LocalTime.of(9, 0)
    val end = LocalTime.of(18, 30)
    val workDuration = Duration.between(start, end)
    println("工作时长(小时): ${workDuration.toHours()}")

    // 4. 带时区的时间转换
    val shanghaiTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"))
    val newYorkTime = shanghaiTime.withZoneSameInstant(ZoneId.of("America/New_York"))
    println("上海时间: $shanghaiTime")
    println("纽约时间: $newYorkTime")

    // 5. 格式化输出
    val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")
    val formatted = LocalDateTime.now().format(formatter)
    println("格式化时间: $formatted")
}

以上涵盖了 Kotlin 中处理时间的核心类及常用方法,实际开发中可根据需求选择合适的类(如仅处理日期用 LocalDate,带时区用 ZonedDateTime 等)。

相关推荐
Kapaseker3 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish20 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker2 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z4 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton5 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream5 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam5 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker5 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php