I have a function that receives a username from a database where the date of birth is stored in a variable of a date type. I then change the date variable to calendar object, then I use the calendar object to calculate the age based on todays date. The function is as shown below
public int calcAge (String username) {
Date date = new Date();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT dob FROM user WHERE username=?",
new String[] {username});
String sDate = new String();
while(cursor.moveToNext()) {
sDate = cursor.getString(0);
}
cursor.close();
DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try{
date = format.parse(sDate);
}
catch (ParseException e){
e.printStackTrace();
}
//Now we have the dob as a date object
//extracting year, month and day from date
Calendar c = Calendar.getInstance();
c.setTime(date);//Converting date to calendar type
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH +1);//We add 1 because the month starts from 0 and not 1
int day = c.get(Calendar.DAY_OF_MONTH);
//return userID;
//return day;
Calendar today = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
//return today.get(Calendar.DAY_OF_YEAR);//198
//return dob.get(Calendar.DAY_OF_YEAR);//203
if (today.get(Calendar.MONTH + 1) < dob.get(Calendar.MONTH)){//We add 1 to today's month to fix it, while the dob month is already fixed
age = age-1;
}
else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)){
if (dob.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH)){
age = age-1;
}
}
return age;
}
I've done some debugging as the result wasn't correct and here is what I found out, this line :
dob.set(year, month, day);
reads the month correctly as stored in the database but then after the line :
if (today.get(Calendar.MONTH + 1) < dob.get(Calendar.MONTH)){//We add 1 to today's month to fix it, while the dob month is already fixed
the month gets changed.