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..
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:
As a side note, there is no need for
yearsBetweento be a long data type (64-bit integer). ThegetYear()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:You can then just plug in your dates where
date1anddate2are like so: