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);
*/
@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