java chrono unit difference between year

476 views Asked by At

i have below code to get difference between two years..

long yearsBetween = ChronoUnit.YEARS.between(
                customDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
                LocalDate.now());

my date value is as below

customDate = 2022-03-07
LocalDate.now() = 2021-10-07

but when i execute ChronoUnit.YEARS.between, it returns "0", but i am expecting "1" as return value. i want to compare only years for the given date and get the difference, excluding days..

1

There are 1 answers

2
Charlie Armstrong On BEST ANSWER

If you want to ignore the month and day components of the LocalDate, you can just get the year from each LocalDate and then compare them, like so:

// Let's say we have two LocalDates, date1 and date2:
LocalDate date1 = LocalDate.of(2021, 10, 6);
LocalDate date2 = LocalDate.of(2022, 3, 7);

// We can get the year for each object and then subtract the two years:
long yearsBetween = date2.getYear() - date1.getYear();

// This will print 1 because 2022 is 1 year ahead of 2021:
System.out.println(yearsBetween);

As a side note, there is no need for yearsBetween to be a long data type (64-bit integer). The getYear() method returns an int (32-bit integer), and I doubt you'll ever have to deal with years that far in the future. We can just use:

int yearsBetween = date2.getYear() - date1.getYear();

You can then just plug in your dates where date1 and date2 are like so:

int yearsBetween = customDate.toInstant().atZone(ZoneId.systemDefault())
        .toLocalDate().getYear()
        - LocalDate.now().getYear();