How to accurately calculate the age of Java on the date of birth

I tried to calculate the age of several months considered in Java, so I can't subtract a few years I also want to tell users that today is their birthday This is my code so far, but I'm afraid it's a little biased It won't tell whether today is a birthday, even if the two dates it compares are equal The first way I tried to calculate was in milliseconds The reason you see two ways to get the current date is because I'm trying to make it work, but I want to show everyone my work so that they can point me in the right direction

The editor clarified that I mean that 2015-1993 can be 22 or 21, depending on their birthday this year I want to make sure I get the right 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));


    }

}

Solution

The following is an example of how to calculate a person's age. If today is their birthday and if today is not their birthday, use the new Java The time package class includes Java 8.0 as part of it

LocalDate today             = LocalDate.Now();
  LocalDate birthday          = LocalDate.of(1982,9,26);
  LocalDate thisYearsBirthday = birthday.with(Year.Now());

  long age = ChronoUnit.YEARS.between(birthday,today);

  if (thisYearsBirthday.equals(today))
  {
     System.out.println("It is your birthday,and your Age is " + age);
  }
  else
  {
     long daysUntilBirthday = ChronoUnit.DAYS.between(today,thisYearsBirthday);
     System.out.println("Your age is " + age + ". " + daysUntilBirthday + " more days until your birthday!");
  }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>