RSS

Age Calculation in C#

15 Mar
 
This post explains how Age can be calculated in C# using DateTime and TimeSpan Classes.
SourceCode:
private string GetAge(DateTime birthday)
{
    DateTime Now = DateTime.Now;
    //Get Years  
    int Years = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year - 1;
    //Get Past Year to calculate months, days and time  
    DateTime dtPastYearDate = birthday.AddYears(Years);
    int Months = 0;
    for (int i = 1; i <= 12; i++)
    {
        if (dtPastYearDate.AddMonths(i) == Now)
        {
            Months = i;
            break;
        }
        else if (dtPastYearDate.AddMonths(i) >= Now)
        {
            Months = i - 1;
            break;
        }
    }
    int Days = Now.Subtract(dtPastYearDate.AddMonths(Months)).Days;
    int Hours = Now.Subtract(dtPastYearDate).Hours;
    int Minutes = Now.Subtract(dtPastYearDate).Minutes;
    int Seconds = Now.Subtract(dtPastYearDate).Seconds;
    return String.Format("Age: {0} Year(s) {1} Month(s) {2} Day(s) {3} Hour(s) {4} Second(s)",
                        Years, Months, Days, Hours, Seconds);
}

 

 

Advertisements
 
Leave a comment

Posted by on March 15, 2013 in ASP Dot Net C#

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: