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

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

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

4条回答
  •  旧巷少年郎
    2020-12-15 23:41

    Or you could just use Calendar.getTimeInMillis():

    long msYear = 1000L * 60 * 60 * 24 * 365;
    long msDiff = c2.getTimeInMillis() - c1.getTimeInMillis();
    System.out.println("Years diff: " + String.valueOf(msDiff / msYear));
    

    Edit This ignores leap years. But if you are looking for an integer representation of the number of years the leap years are irrelevant for periods shorter than half a millennium or so.

    This is plenty of exactness for calculating somebody's age, for example. But not accurate enough to tell their birthday.

    If you need your year difference more exact than to three significant digits within a human lifespan (approximately 80.00 years vs 80.05), you should use the "official" solution.

    If not, there's no particular reason to put in extra effort for a degree of precision you are not going to use.

提交回复
热议问题