You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Kotlinx.LocalDateTime获取重置为00:00的当前日期?

获取当天起始时刻(00:00:00)的实现方案

针对你的需求,用kotlinx-datetime库有两种简洁的方式可以将时间重置为当天00:00:00:

方法一:截断LocalDateTime到日期精度

利用LocalDateTime的truncatedTo方法,直接把时分秒等时间字段置为0:

import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlinx.datetime.DateTimeUnit

val todayStart = Clock.System.now()
    .toLocalDateTime(TimeZone.currentSystemDefault())
    .truncatedTo(DateTimeUnit.DATE)

方法二:从LocalDate构建起始时刻

先提取当前日期,再通过atStartOfDay()生成当天的00:00:00时刻,逻辑更直观:

import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime

val today = Clock.System.now()
    .toLocalDateTime(TimeZone.currentSystemDefault())
    .date
val todayStart = today.atStartOfDay()

补充说明

两种方法效果完全一致,都能得到当前时区下当天的起始时刻。如果需要将结果转回Instant(比如后续要和Clock的时间格式统一),可以用todayStart.toInstant(TimeZone.currentSystemDefault())。

内容的提问来源于stack exchange,提问作者testivanivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 00:43:11