kotlintimezonekotlinx-datetime

How to get current date with reset time 00:00 with Kotlinx.LocalDateTime?


I'm using kotlinx.Clock.now() to get current date. Next I need to convert this date to LocalDateTime, here is my code:

Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())

It works well. However, I need to get today's day, but exactly the beginning of today's day, that is 00:00:00. Is it possible to reset the time to 00:00:00?


Solution

  • First, get today's date as a LocalDate.

    You can do it the long way:

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

    Or you can simplify using Clock.todayIn:

    val tz = TimeZone.currentSystemDefault()
    val today = Clock.System.todayIn(tz)
    

    With either of the above, you can now get the starting Instant of the day using LocalDate.atStartOfDayIn.

    val startInstant = today.atStartOfDayIn(tz)
    

    From there if you need a LocalDateTime, you can get that as well:

    val start = startInstant.toLocalDateTime(tz)
    

    Putting it all together:

    val tz = TimeZone.currentSystemDefault()
    val start = Clock.System.todayIn(tz).atStartOfDayIn(tz).toLocalDateTime(tz)
    

    I recommend atStartOfDayIn, as it will correctly return the starting point of the day - which is not necessarily 00:00.

    For example, on March 12th 2023 in Cuba (tz: America/Havana), the day started at 01:00, because it was the first day of daylight saving time, and in that particular time zone, the transition occurs at 00:00. (In other words, the local time goes from 23:59 to 01:00 on that day.). There are many other cases like this.