Search code examples
javadateiso8601

Get number of years with a date in ISO8601


I'm trying to get number of years since a date provided with a string in a "2013-12-06" format. I want to compare it to today (2020-21-06) and have the number of years that I can put in an int.

For exemple, I receive

String d = "2013-12-06"

Today's date is the 2020/21/06.

How do I get the difference beetween the two in years?

In this example it would be 6 years.

Thank you very much!


Solution

  • java.time.Year

    import java.time.Year;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    public class Main {
        public static void main(String[] args) {
            Year year = Year.parse("2013-12-06", DateTimeFormatter.ISO_DATE);
            long years = year.until(Year.now(), ChronoUnit.YEARS);
    
            System.out.println(years);
        }
    }
    

    Output:

    7