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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With