Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...