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

753 Views Asked by At

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?

2

There are 2 best solutions below

0
Matt Johnson-Pint On BEST ANSWER

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.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.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.

2
deHaar On

LocalDateTime has a constructor that takes a LocalDate and a LocalTime as arguments.

You can pass the the desired LocalDate to it along with LocalTime.MIN, which will result in a LocalDateTime at the specific date with a local time of 00:00:00.

Have a look at the sources of the kotlinx-datetime project