find current age

Rock Hitman 46 Reputation points
2021-08-23T16:29:35.443+00:00

Hi, I will be getting from source the date format as string mm/dd/yyyy ("11/04/1920").
I would like to know is there any easy logic to find out the Age.
I would like to know if the Age is >=16

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2021-08-23T17:05:15.937+00:00

    Check this method:

    string example = "11/04/1920";
    DateTime date = DateTime.Parse( example, CultureInfo.GetCultureInfo( "en-US" ) );
    DateTime today = DateTime.Today;
    int age = today.Year - date.Year;
    if( date.AddYears( age ) > today ) age -= 1;
    
    if( age >= 16 )
    {
       // . . .
    }
    

1 additional answer

Sort by: Most helpful
  1. Ravi Shankar Kakarla 161 Reputation points
    2021-08-23T18:02:52.33+00:00

    Step 1: Create a method to Check the Age

    public static int GetAge(DateTime dob)
    {

    return DateTime.Now.AddYears(-dob.Year).Year;  
    

    }

    Step 2: Call the method

       string inputDate="11/04/1920";
    
       if(GetAge(Convert.ToDateTime(inputDate))>=16)
        {
         // TODO:
        }
        else
        {
           //TODO:
        }
    
    0 comments No comments