Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

android

I am trying to determine an age in years from a certain date. Does anyone know a clean way to do this in Android? I have the Java api available obviously, but the straight-up java api is pretty weak, and I was hoping that Android has something to help me out.

EDIT: The multiple recommendations to use Joda time in Android worries me a bit due to Android Java - Joda Date is slow and related concerns. Also, pulling in a library not shipped with the platform for something this size is probably overkill.

like image 819
Micah Hainline Avatar asked Oct 26 '11 17:10

Micah Hainline


People also ask

Can you calculate the time between two dates?

How do I go about calculating the days between two dates? To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months.


1 Answers

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.

like image 179
sinuhepop Avatar answered Sep 23 '22 08:09

sinuhepop