Skip to content
Advertisement

Remaining days taking one date as a reference in Java

I have a variable of type LocalDateTime which has a date stored, for example 14/03/2020. I would like to know how I can get the days remaining to be again the 14th day of the month 3; in this case (from August 1, 2022), there are 225 days. I really have no idea how to get that value.

Advertisement

Answer

Determine a year by comparing the date portion of the current and reference dates. If the date has passed already, use next year; otherwise, use the current year. Then combine this year with the month and day of month from the reference date to yield the anniversary. Finally, compute the difference in days between the reference date and the anniversary.

static LocalDate nextAnniversary(LocalDate date, LocalDate today) {
    MonthDay anniversary = MonthDay.from(date);
    int year = today.getYear();
    if (anniversary.isBefore(MonthDay.from(today))) year += 1;
    return anniversary.atYear(year);
}

An example of this function in use:

LocalDateTime stored = LocalDateTime.of(LocalDate.of(2020, 3, 14), LocalTime.NOON);
LocalDate today = LocalDate.now(); /* Or, better: LocalDate.now(clock) */
LocalDate anniversary = nextAnniversary(stored, today);
long daysUntil = today.until(stored, ChronoUnit.DAYS);

Update: This took a few tries to get right. Leap day complicates things; it is best to determine the year first, then to combine it with the original month and day, rather than to increment a past date by one year. (h/t Basil Bourque and Ole V.V.)

8 People found this is helpful
Advertisement