Skip to content

Instantly share code, notes, and snippets.

@mshwf
Created April 20, 2019 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshwf/e1355a03063f09b47190bf06584e163f to your computer and use it in GitHub Desktop.
Save mshwf/e1355a03063f09b47190bf06584e163f to your computer and use it in GitHub Desktop.
public static string ToAgeString(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");
}
public static string AgeDiff(DateTime bigger, DateTime _smaller)
{
DateTime smaller = _smaller;
int months = smaller.Month - bigger.Month;
int years = smaller.Year - bigger.Year;
if (smaller.Day < bigger.Day)
{
months--;
}
if (months < 0)
{
years--;
months += 12;
}
int days = (smaller - bigger.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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment