locked
age calculator result is worng RRS feed

  • Question

  • private void btncalcu_Click(object sender, RoutedEventArgs e)
            {
                DateTime birthday = this.birthdate.Date.DateTime;
                DateTime calcudate = this.Currentdate.Date.DateTime;
                
               
                result.Text +="You are : "+CalculateAge(birthday, calcudate) + " year old" ;
                
                TimeSpan myage1 = calcudate.Subtract(birthday);
    
                result.Text += String.Format("\n Month : {0}", (birthday.Month - calcudate.Month).ToString());
                result.Text += String.Format("\n Days : " + (calcudate.Day - birthday.Day).ToString());
                result.Text += String.Format("\n Your Age in Days : " + myage1.TotalDays).ToString();
                result.Text += String.Format("\nYour Age in Hours : " + myage1.TotalHours).ToString();
                result.Text += String.Format("\nMinutes Since your birth : " + myage1.TotalMinutes).ToString();
                result.Text += String.Format("\nSeconds Since your birth : " + myage1.TotalSeconds).ToString();
                result.Text += String.Format("\nMilliseconds Sice your birth : " + myage1.TotalMilliseconds).ToString();
    
            }
            public int CalculateAge(DateTime birthDate, DateTime now)
            {
                int age = now.Year - birthDate.Year;
                if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
                return age;
            }
    month calculation wrong result
    Friday, January 31, 2014 7:24 AM

Answers

  • Try this implementation

    int age = now.Year - birthDate.Year;
    if (now < birthDate.AddYears(age)) age--;
    return age;

    Friday, January 31, 2014 7:35 AM