Home > OS >  How to get the number of days between LocalDateTime instances, ignoring the time
How to get the number of days between LocalDateTime instances, ignoring the time

Time:08-14

I almost caused an online bug by using LocalDateTime until,For example:

@Test
public void test(){

    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    LocalDateTime startTime = LocalDateTime.parse("2022-08-09 11:00:00", df);

    LocalDateTime endTime = LocalDateTime.parse("2022-08-11 10:00:00", df);

    System.out.println(startTime.until(endTime, ChronoUnit.DAYS));
}

I initially thought he should return 2 day , but it turned out to be 1 day !

Then I looked at the corresponding source code, and I now seem to understand it: if more than one day, less than two days, it will only return one day.

I want to ask if there is a tool available in Java or Spring that meets my needs.

I want it to go back to 2 days, which fits people's intuition.

Of course, I could wrap a utility class to do this, but I wonder if there is an implementation available in Java?

My business scenario looks like this: if it is > 3 days, something will be done.

For example:

if the start time is 2022-08-11 10:00:00, the operation will be performed after 2022-08-14 10:00:00.

However, when I call the API at 2022-08-14 11:00:00, I return 3, which does not meet the condition > 3.

Therefore, The task is still not executed, causing the bug.

CodePudding user response:

My business scenario looks something like this: If the current time is within three days of a certain time, something will be done.

That sounds a lot like you are working with dates rather than dates times. Therefore, you should use a LocalDate instead.

You can convert both startTime and endTime to LocalDate like this:

System.out.println(
    startTime.toLocalDate().until(endTime.toLocalDate(), ChronoUnit.DAYS)
);

Or better, just parse the strings as LocalDates in the first place, not LocalDateTime.

var startTime = LocalDate.parse("2022-08-09 11:00:00", df);

var endTime = LocalDate.parse("2022-08-11 10:00:00", df);

System.out.println(startTime.until(endTime, ChronoUnit.DAYS));

CodePudding user response:

Just set startTime at the same hour, minutes and seconds of endTime (or viceversa). Then compare them and it will give you 2 days.

  • Related