Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there.

Im doing a c# desktop application and trying to convert a "Date Of Birth" into an "Age".

Problem is that I retrieve the "Date Of Birth" from an SQL SERVER 2008 server as a nvarchar and save it in C# as a string.

Any help?
Posted
Comments
TRK3 14-Sep-11 16:54pm    
What is the format of the data in the database? Are they all the same format or do they vary?

Try this:
C#
String dob = "2010/01/01";//read from your database to get dob, just an example
DateTime dateOfBirth = DateTime.Parse( dob );
Int32 age = DateTime.Now.Year - dateOfBirth.Year;
//age=1 in above code


Good luck
 
Share this answer
 
Try
C#
public static int GetAge(string strDate)
     {
         DateTime birthDate = DateTime.Parse(strDate);
         DateTime n = DateTime.Now; 
         int age = DateTime.Now.Year - birthDate.Year;

         if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
             age--;

         return age;
     }
 
Share this answer
 
Or as an extension method:

C#
public static class ExtensionMethods
{
    public static int Age(this DateTime dt)
    {
        TimeSpan span = DateTime.Now.Date - dt.Date;
        return Math.Min(1, span.TotalDays % 365);
    }
}
 
Share this answer
 
Comments
AspDotNetDev 14-Sep-11 19:51pm    
Not sure this would be 100% accurate, on account of leap years.
#realJSOP 15-Sep-11 4:47am    
I think it would be close enough if we're talking about the age of a human, and not the age of something like the earth.
The exact age depends on the requesting moment. You have to consider days-per-month and leap years.

The DateDiff class of the Time Period Library for .NET[^] is considering these aspects:
C#
// ----------------------------------------------------------------------
public int Age( DateTime dob )
{
  return new DateDiff( dob ).ElapsedYears;
} // Age
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900