I am trying to calculate age in java that accounts for months, so just subtracting years will not work. I also want to tell the user if today is their birthday. Here is the code I have so far, but I am afraid it is a bit off. It also will not tell if today is the birthday even though the two dates it's comparing are equal. The way I tried to originally calculate was using milliseconds. The reason you see 2 ways of getting the current date is because I was trying something to get it working, but wanted to show everyone my work so that they could point me in the right direction.
EDIT FOR CLARIFICATION what I mean is 2015-1993 can either be 22 years old or 21 depending if their birthday has already passed this year. I want to be sure that I get the correct age with this in mind.
public class ShowAgeActivity extends AppCompatActivity {
private TextView usersAge;
private static long daysBetween(Date one, Date two)
{
long difference = (one.getTime()-two.getTime())/86400000; return Math.abs(difference);
}
private Date getCurrentForBirthday()
{
Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
int birthdayYear = birthday.getYear() + 1900;
Calendar cal = Calendar.getInstance();
cal.set(birthdayYear, Calendar.MONTH, Calendar.DAY_OF_MONTH);
Date current = cal.getTime();
return current;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_age);
Date birthday = (Date) this.getIntent().getExtras().get("TheBirthDay");
Date currentDay = Calendar.getInstance().getTime();
long age = daysBetween(birthday,currentDay)/365;
usersAge =(TextView)findViewById(R.id.ageTextView);
if (birthday.compareTo(getCurrentForBirthday()) == 0 )
{
usersAge.setText("It is your birthday, and your Age is " + String.valueOf(age));
}
usersAge.setText("Your Age is " + String.valueOf(age));
}
}