-1

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.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67

1 Answers1

0

Perhaps consider using SQL to calculate the age.

e.g.

public int calcAge (String username) {
    int age = -1; // age if no user
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
            "user",
            new String[]{"substr(date('now'),1,4) - substr(dob,1,4) - (strftime('%j',replace(dob,'/','-')) > strftime('%j','now')) AS age"},
            "username=?",
            new String[]{username},
            null,null,null
    );
    //Cursor cursor = db.rawQuery("SELECT substr(date('now'),1,4) - substr(dob,1,4)  - (strftime('%j',replace(dob,'/','-')) > strftime('%j','now')) AS age FROM user WHERE username=?", new String[]{username});
    if (cursor.moveToFirst()) {
        age = cursor.getInt(cursor.getColumnIndex("age"));
    }
    cursor.close();
    return age;
}
  • Note commented out line is rawQuery version, while the uncommented out uses the SQLiteDatabase query method.
  • The above assumes the date is stored in the YYYY/MM/DD format (not a supported date/time format so hence the need to replace /'s with -'s )
  • Note that if a non-existent username is provided as the argument then the age will be returned as -1.

The above has been tested using a database that contains :-

enter image description here

And then running :-

Log.d("NEXTACTIVITY","Age of " + current_username + " = " + db.calcAge(current_username));
  • where current_username is fred

The Log contains :-

D/NEXTACTIVITY: Age of fred = 64

The query itself substracts the dob year from the current year (the age in years) but then checks if the dob month/day is > then the current month/day. As false equates to 0 and true to 1 this value is subtracted from the age to adjust for the current year.

MikeT
  • 51,415
  • 16
  • 49
  • 68