How to catch the date and minimum time of the day with Localdatetime

Asked

Viewed 979 times

4

I have this dateHora in the database:

21/07/18 15:52:00,000000000

When the query passes by parameter one LocalDateTime, I want to list all the dates that start the day. How to get the minimum date with the LocalDateTime, and query this data? Remembering that you have in the database the milliseconds.

I tried to do the:

 LocalDateTime.Now().MIN

But that way the date comes wrong.

1 answer

2


MIN is a constant that represents the least possible value for a LocalDateTime (see the documentation). More precisely, it represents 1 January of the year -999999999 (year "minus 999 million") at midnight. Maybe that’s why the date was wrong in your test.

Based on the question title ("How to get the date and minimum time of the day with LocalDateTime"): "minimum date and time of day" does not make much sense, because a date represents a specific day and has no way to have a "minimum date of the day".

Anyway, I understand that you actually want the "minimum time of the day" of a certain date. That is, midnight of a given day (since the day begins at midnight, and therefore this would be the "minimum hour", that is, the lowest possible value for the hour of the day).

For this you can use the method with passing a LocalTime which corresponds to midnight. This method is useful if you have a LocalDateTime any and need to change their time to midnight:

// data e hora atual
LocalDateTime dateTime = LocalDateTime.now();
// mudar horário para meia-noite
LocalDateTime inicioDia = dateTime.with(LocalTime.MIDNIGHT);

But if you need to build an object that corresponds to today and set the time to midnight, you can also do this using a LocalDate to construct the current date (day, month and year) and then use the method atStartOfDay, that returns a LocalDateTime with set time for midnight:

// data de hoje (dia, mês e ano)
LocalDate hoje = LocalDate.now();
// setar horário para meia-noite
LocalDateTime inicioDia = hoje.atStartOfDay();

LocalDate also has the method atTime, that allows you to pass a LocalTime with the time you want (in case you need any value other than midnight).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.