How can I find the number of years between two dates? How can I find the number of years between two dates? android android

How can I find the number of years between two dates?


import java.util.Calendar;import java.util.Locale;import static java.util.Calendar.*;import java.util.Date;public static int getDiffYears(Date first, Date last) {    Calendar a = getCalendar(first);    Calendar b = getCalendar(last);    int diff = b.get(YEAR) - a.get(YEAR);    if (a.get(MONTH) > b.get(MONTH) ||         (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {        diff--;    }    return diff;}public static Calendar getCalendar(Date date) {    Calendar cal = Calendar.getInstance(Locale.US);    cal.setTime(date);    return cal;}

Note: as Ole V.V. noticed, this won't work with dates before Christ due how Calendar works.


tl;dr

ChronoUnit.YEARS.between(     LocalDate.of( 2010 , 1 , 1 ) ,     LocalDate.now( ZoneId.of( "America/Montreal" ) ) )

java.time

The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );

Dump to console.

System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;

start: 2010-01-01 | stop: 2016-09-06 | years: 6


Table of all date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android


I would recommend using the great Joda-Time library for everything date related in Java.

For your needs you can use the Years.yearsBetween() method.