What is the best way to calculate the age in years from a birth date in sqlite3?
IT is very dificult to do in sqllite... so better you retrive the birth date from the database nd then add this logic
private Calendar mConvert_Date_To_Calendar(String dateToConvert)
{
// TODO Auto-generated method stub
try
{
Calendar calConversion = Calendar.getInstance();
Date date1 = null;
try
{
date1 = new SimpleDateFormat("dd/MM/yy").parse(dateToConvert);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
calConversion.setTime(date1);
System.out.println("mConvert_Date_To_Calender date1: " + date1
+ "caleder converted done:" + calConversion.getTime());
return calConversion;
}
catch (Exception e)
{
e.printStackTrace();
Log.i(TAG, "" + e);
return null;
}
}
private Calendar myCurrentCalender()
{
try
{
Calendar myCurrentCal = Calendar.getInstance();
myCurrentCal.set(myCurrentCal.get(Calendar.YEAR), myCurrentCal.get(Calendar.MONTH),
myCurrentCal.get(Calendar.DAY_OF_MONTH));
return myCurrentCal;
}
catch (Exception e)
{
e.printStackTrace();
Log.e(TAG, "Unable to get current calendar!");
return null;
}
}
public int daysBetween(Date d1, Date d2)
{
System.out.println("calculated age :"
+ (((d2.getTime() - d1.getTime()) / ((24 * 1000 * 60 * 60)) / 365)));
return (int) (((d2.getTime() - d1.getTime()) / (24 * 1000 * 60 * 60)) / 365);
}
The first function will calculate the birth date in calendar format, second will calculate current date, the third will find the difference between the two. These functions shud be called as shown below
dateOfBirth = mConvert_Date_To_Calendar(age);
currentDate = myCurrentCalender();
candidateAge = daysBetween(dateOfBirth.getTime(), currentDate.getTime());
"candidateAge" will have the age.
You can convert the dates to floating point numbers and subtract…
cast(strftime('%Y.%m%d', 'now') - strftime('%Y.%m%d', dob) as int)
…where dob
is a valid SQLite time string.