Skip to content

Instantly share code, notes, and snippets.

@faisalman
Last active June 8, 2023 11:40
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save faisalman/1724253 to your computer and use it in GitHub Desktop.
Save faisalman/1724253 to your computer and use it in GitHub Desktop.
Calculate Age (Years + Months + Days) in C#
/**
* Calculate Age in C#
* https://gist.github.com/faisalman
*
* Copyright 2012-2013, Faisalman <fyzlman@gmail.com>
* Licensed under The MIT License
* http://www.opensource.org/licenses/mit-license
*/
using System;
public class Age
{
public int Years;
public int Months;
public int Days;
public Age(DateTime Bday)
{
this.Count(Bday);
}
public Age(DateTime Bday, DateTime Cday)
{
this.Count(Bday, Cday);
}
public Age Count(DateTime Bday)
{
return this.Count(Bday, DateTime.Today);
}
public Age Count(DateTime Bday, DateTime Cday)
{
if ((Cday.Year - Bday.Year) > 0 ||
(((Cday.Year - Bday.Year) == 0) && ((Bday.Month < Cday.Month) ||
((Bday.Month == Cday.Month) && (Bday.Day <= Cday.Day)))))
{
int DaysInBdayMonth = DateTime.DaysInMonth(Bday.Year, Bday.Month);
int DaysRemain = Cday.Day + (DaysInBdayMonth - Bday.Day);
if (Cday.Month > Bday.Month)
{
this.Years = Cday.Year - Bday.Year;
this.Months = Cday.Month - (Bday.Month + 1) + Math.Abs(DaysRemain / DaysInBdayMonth);
this.Days = (DaysRemain % DaysInBdayMonth + DaysInBdayMonth) % DaysInBdayMonth;
}
else if (Cday.Month == Bday.Month)
{
if (Cday.Day >= Bday.Day)
{
this.Years = Cday.Year - Bday.Year;
this.Months = 0;
this.Days = Cday.Day - Bday.Day;
}
else
{
this.Years = (Cday.Year - 1) - Bday.Year;
this.Months = 11;
this.Days = DateTime.DaysInMonth(Bday.Year, Bday.Month) - (Bday.Day - Cday.Day);
}
}
else
{
this.Years = (Cday.Year - 1) - Bday.Year;
this.Months = Cday.Month + (11 - Bday.Month) + Math.Abs(DaysRemain / DaysInBdayMonth);
this.Days = (DaysRemain % DaysInBdayMonth + DaysInBdayMonth) % DaysInBdayMonth;
}
}
else
{
throw new ArgumentException("Birthday date must be earlier than current date");
}
return this;
}
}
/**
* Usage example:
* ==============
* DateTime bday = new DateTime(1987, 11, 27);
* DateTime cday = DateTime.Today;
* Age age = new Age(bday, cday);
* Console.WriteLine("It's been {0} years, {1} months, and {2} days since your birthday", age.Year, age.Month, age.Day);
*/
@nasi-be-guling
Copy link

Good Job man...
You safe my time hard code these thing..
Thank you.

Copy link

ghost commented Feb 7, 2015

Well done!

@markrullo
Copy link

Thank you, very helpful. I've added this to my instance:

    public string AgeString
    {
        get
        {
            string ageString = string.Empty;

            if (Years < 1 && Months < 1)
            {
                ageString = string.Format("{0} Days", Days);
            }
            else if (Years < 3)
            {
                ageString = string.Format("{0} Months {1} Days", Years * 12 + Months, Days);
            }
            else
            {
                ageString = string.Format("{0} Y {1} M {2} D", Years, Months, Days);
            }

            return ageString;
        }
    }

@vipul2008
Copy link

Gud One..
if I calculate birthday for date '15-Feb-1986' then it returns '29 Years, 6 Months, 15 Days' but it the days should be 18 when i am comparing the results with windows date calculator.
might be Leap Year calculation issue

@avinewman
Copy link

This age.cs was very helpful. Thank you @faisalman. I also used @markrullo's AgeString but modified it for my own purposes. The version below shows age in Years and Months if > 1 year. If < 1 year it shows only Months and Days. If younger than 1 month, it only shows Days. Finally, it accounts for proper singularization and pluralization.

i.e.
0 days,
1 day,
1 month 0 days,
2 months 1 day,
1 year 0 months,
2 years 1 month,
3 years 3 months,
et cetera...

public string AgeString
{
  get
  {
    string ageString = string.Empty;
    if (Years == 1 && Months == 1)
    {
      ageString = string.Format("1 Year 1 Month");
    }
    else if (Years == 1)
    {
      ageString = string.Format("1 Year {0} Months", Months);
    }
    else if (Years < 1 && Months == 1 && Days == 1)
    {
      ageString = string.Format("1 Month 1 Day");
    }
    else if (Years < 1 && Months == 1)
    {
      ageString = string.Format("1 Month {0} Days", Days);
    }
    else if (Years < 1 && Months < 1 && Days == 1)
    {
      ageString = string.Format("{0} Day", Days);
    }
    else if (Years < 1 && Months < 1)
    {
      ageString = string.Format("{0} Days", Days);
    }
    else if (Years < 1 && Days == 1)
    {
      ageString = string.Format("{0} Months {1} Day", Years * 12 + Months, Days);
    }
    else if (Years < 1)
    {
      ageString = string.Format("{0} Months {1} Days", Years * 12 + Months, Days);
    }
    else if (Years >= 2 && Months == 1)
    {
      ageString = string.Format("{0} Years {1} Month", Years, Months);
    }
    else // if (Years >= 2 && Months != 1)
    {
      ageString = string.Format("{0} Years {1} Months", Years, Months);
    }
    return ageString;
  }

public static string GetAgeString(DateTime bday)
{
   return new Age(bday, DateTime.Today).AgeString;
}

@kmaarouf
Copy link

kmaarouf commented May 18, 2016

Thanks to all of you, special thanks to @faisalman >

This is working fine with me :)

public string AgeString
    {
        get
        {
            string ageString = string.Empty;

            if (Years >= 1)
            {
                if (Years == 1)
                {
                    ageString = string.Format("{0} Year", Years);
                }
                else
                {
                    ageString = string.Format("{0} Years", Years);
                }

                if (Months >= 1)
                {
                    if (Months == 1)
                    {
                        ageString += string.Format(" {0} Month", Months);
                    }
                    else
                    {
                        ageString += string.Format(" {0} Months", Months);
                    }

                    if (Days >= 1)
                    {
                        if (Days == 1)
                        {
                            ageString += string.Format(" {0} Day", Days);
                        }
                        else
                        {
                            ageString += string.Format(" {0} Days", Days);
                        }
                    }
                }
            }
            return ageString;
        }
    }

@Abrahamlet
Copy link

Awesome code. Thanks for posting, @faisalman. Thanks also to @avinewman and @kmaarouf.
One suggestion, though: include a calculation for weeks.

:)

@crashoverride002
Copy link

Thanks for this. Amazing how hard it is to find a library for this.

Is it possible to request a few features? or I could share the code we have added to ours.

a bool IsBirthday function which will return true if its there birthday.

How does this class handle leap birthdays?

Is it possible for a Unit test class that tests different outcomes?

@palak6041
Copy link

Is there any extension to this class which can calculate Date back from output of this program (e.g. calculate Date back from Year , Month and Days)?

@RetiredQQ
Copy link

RetiredQQ commented Apr 15, 2018

public static void CalculateAge(DateTime DayOfBirth)
		{
			var dt = DateTime.Now;
			var years = new DateTime(DateTime.Now.Subtract(DayOfBirth).Ticks).Year - 1;
			var pastYear = DayOfBirth.AddYears(years);
			var months = 0;
			for ( int i = 1; i <= 12; i++)
			{
				if (pastYear.AddMonths(i) == dt)
				{
					months = i;
				}
				else if (pastYear.AddMonths(i) >= dt)
				{
					months = i - 1;
					break;
				}
			}
			
			var days = dt.Subtract(pastYear.AddMonths(months)).Days;
			
			Console.WriteLine(string.Format("It's been {0} years, {1} months, and {2} days since your birthday", years,months, days));
		}

@TarafderGoutam
Copy link

Wow, fantastic. Thank you so mush..

@faisalman
Copy link
Author

For further development, this code has been moved to https://github.com/faisalman/age-calc-cs, any feedback or suggestions are welcome.. Thank you 😊

@edwardzxw
Copy link

Thanks a lot! It saves my day...

@Venkat-ramana-reddy
Copy link

Im learning can anyone please explain the code ?

@yasserahmmed1
Copy link

I use this code to calculate Age and it is very simple:
`DateTime birthdays = DateTime.Parse(dateTimePicker1.Text);
DateTime dateNow = DateTime.Parse(dateTimePicker2.Text);
TimeSpan urBirthday = dateNow - birthdays;
label3.Text = urBirthday.Days.ToString();
label3.Text += "\n All Day :" + string.Format("{0} total days ",urBirthday.TotalDays);
int nowMonth = dateNow.Month;
int birthMonth = birthdays.Month;
int nowYears = dateNow.Year;
int birYear = birthdays.Year;

            int nowDays = dateNow.Day;
            int biDays = birthdays.Day;
            int yy = nowYears - birYear;
            int mm = nowMonth - birthMonth;
            int dd = nowDays - biDays;
            if (mm < 0)
            {
                yy--;
                mm = mm + 12;
            }
            if (dd < 0)
            {
                mm--;
                dd = dd + 31;
            }

            label3.Text += "\n\n year :" + string.Format("{0} years",yy);
            label3.Text += "\n month :" + string.Format("{0} months",mm);
            label3.Text += "\n days :" + string.Format("{0} days",dd);`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment