How do I calculate the number of years difference between 2 dates?

前端 未结 4 909
一向
一向 2020-12-15 23:15

How do I calculate the number of years difference between 2 calendars in Java?

4条回答
  •  旧时难觅i
    2020-12-15 23:36

    First you need to determine which one is older than the other. Then make use of a while loop wherein you test if the older one isn't after() the newer one. Invoke Calendar#add() with one (1) Calendar.YEAR on the older one to add the years. Keep a counter to count the years.

    Kickoff example:

    Calendar myBirthDate = Calendar.getInstance();
    myBirthDate.clear();
    myBirthDate.set(1978, 3 - 1, 26);
    Calendar now = Calendar.getInstance();
    Calendar clone = (Calendar) myBirthDate.clone(); // Otherwise changes are been reflected.
    int years = -1;
    while (!clone.after(now)) {
        clone.add(Calendar.YEAR, 1);
        years++;
    }
    System.out.println(years); // 32
    

    That said, the Date and Calendar API's in Java SE are actually epic failures. There's a new Date API in planning for upcoming Java 8, the JSR-310 which is much similar to Joda-Time. As far now you may want to consider Joda-Time since it really eases Date/Time calculations/modifications like this. Here's an example using Joda-Time:

    DateTime myBirthDate = new DateTime(1978, 3, 26, 0, 0, 0, 0);
    DateTime now = new DateTime();
    Period period = new Period(myBirthDate, now);
    int years = period.getYears();
    System.out.println(years); // 32
    

    Much more clear and concise, isn't it?

提交回复
热议问题