There is no shortcut in getting a contact’s age in Android. What I did instead was to get the birthday of the contact (if any is provided) and subtracted that from the current year.

The output of a contact’s birthday is a string formatted date with dashes (-) so I had to make a helper method to parse it; get the month, date and year; convert it to a Date object, then do calculation to get the age of the contact.

Check out the helper method below.

And this is how I retrieved the birthday of the contact from the contact list. Once retrieved, I parsed the output and passed it to the calculateAge() method.

Just now I encountered another weird behavior in Android. Using the Calendar class does not yield the desired results. So I have a custom date as a String, converted it to a java.util.Date object then passed it to the Calendar object’s setTime() method.

When I called the Calendar object’s get() method using Calendar.YEAR as the parameter, it returned the current year instead of the year that was set to it.

I have no idea why it acts like this but since this behavior persists in the Android emulator, the same should happen in a real smartphone that runs Android.

Better avoid using the Calendar class if it does not give you the results that you want.

Related Posts Plugin for WordPress, Blogger...