0

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!

2 Answers2

1

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0
import java.time.LocalDate;
import java.lang.Math;
import java.lang.Integer;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LocalDate now = LocalDate.now();
        String nowTime = now.toString();
        String d = "2013-12-06";
        String year = d.substring(0, 4);
        String NowYear = nowTime.substring(0, 4);
        int yearInt = Integer.parseInt(year);
        int NowYearInt = Integer.parseInt(NowYear);
        
        int diff = NowYearInt - yearInt;
        System.out.println(diff);
    }

}

The old fashioned way. Prints 7. Works if the year is from 1000 - 2020.

new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34