-1

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..

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
pappu_kutty
  • 2,378
  • 8
  • 49
  • 93
  • 3
    The dates you've given are only 5 months apart though. Do you want it to only consider the year portion of the date? So 2021-12-31 and 2022-01-01 would be 1 year apart, but 2022-01-01 and 2022-12-31 would be 0 years apart? This part of your question could be made clearer. – Charlie Armstrong Oct 07 '21 at 04:03
  • i have mentioned , that i need to compare only years not dates in question.. – pappu_kutty Oct 07 '21 at 04:05
  • Got it, I was just a little confused by the wording. Thank you for clarifying. – Charlie Armstrong Oct 07 '21 at 04:06

1 Answers1

4

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();
Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25
  • comparing date.getYear() and getting difference is what i did.. this works.. Thanks.. – pappu_kutty Oct 07 '21 at 04:24
  • 2
    No need to go the `LocalDate` detour: `int yearsBetween = customDate.toInstant() .atZone(ZoneId.systemDefault()).getYear() - Year.now().getValue();` Another possibility would be `long yearsBetween2 = Year.now().until( customDate.toInstant().atZone(ZoneId.systemDefault()), ChronoUnit.YEARS);` – Holger Oct 07 '21 at 15:25