Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why the error giving -> String was not recognized as a valid DateTime.

My cs code is given below

C#
private void button1_Click(object sender, EventArgs e)
        {
            string d = textBox1.Text;
            DateTime dob = Convert.ToDateTime(d.ToString());
            int age = CalculateYorAge(dob);
            MessageBox.Show(dob.ToString());
            label1.Text = age.ToString();
         }    

public static int CalculateYorAge(DateTime birthDaydate)
        {
            int yearsAge = DateTime.Now.Year - birthDaydate.Year;
            if (DateTime.Now.Month < birthDaydate.Month || (DateTime.Now.Month == birthDaydate.Month && DateTime.Now.Day < birthDaydate.Day))                yearsAge--; return yearsAge;
        }
Posted
Updated 15-Mar-12 21:18pm
v2

Add below line instead of
C#
DateTime dob = Convert.ToDateTime(d.ToString());

If you are entering string in dd/MM/yyyy then use below code else change accordingly.
C#
DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
 
Share this answer
 
v2
i am not getting any error trying your code the thing is that, what are you giving input in texbox ? if i given as: 5/8/1987 it displays as 24. fine !

try:
C#
DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy", null);
 
Share this answer
 
v3
Comments
Janardan Pandey 16-Mar-12 3:36am    
but please input 17/12/1984 and check it.
member60 16-Mar-12 3:45am    
see my updated solution.or just:
DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy", null);

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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