0

I've made a very simple (inaccurate) program that calculates your age. I want to make it accurate by calculating leap years and taking into account that every month has a different amount of days. Any help how to do that and where to start? Thanks!

using System;

public class Program
{
    public static void Main()
    {
        float currentDay = 22;
        float currentMonth = 2;
        float currentYear = 2020;

        Console.WriteLine("Enter your date of birth: (eg: 13/04/1998)");
        Console.Write("Day: ");
        int dayNum = Convert.ToInt16(Console.ReadLine());
        Console.Write("Month: ");
        int monthNum = Convert.ToInt16(Console.ReadLine());
        Console.Write("Year: ");
        int yearNum = Convert.ToInt16(Console.ReadLine());

        float birthDay = (currentDay - dayNum) / 365;
        float birthMonth = (currentMonth - monthNum) / 12;
        float birthYear = currentYear - yearNum;

        float age = birthYear + birthMonth + birthDay;

        Console.WriteLine("Your age is: " + age);



    }
}

1 Answers1

0

My Suggestion is to you something like the following:

public static string ToAgeString(this DateTime dob)
{
    DateTime today = DateTime.Today;

    int months = today.Month - dob.Month;
    int years = today.Year - dob.Year;

    if (today.Day < dob.Day)
    {
        months--;
    }

    if (months < 0)
    {
        years--;
        months += 12;
    }

    int days = (today - dob.AddMonths((years * 12) + months)).Days;

    return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                         years, (years == 1) ? "" : "s",
                         months, (months == 1) ? "" : "s",
                         days, (days == 1) ? "" : "s");
}