Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
Why the error giving -> String was not recognized as a valid DateTime.
My cs code is given below
private void button1_Click(object sender, EventArgs e)
            string d = textBox1.Text;
            DateTime dob = Convert.ToDateTime(d.ToString());
            int age = CalculateYorAge(dob);
            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 15-Mar-12 21:14pm
Edited 15-Mar-12 21:18pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Add below line instead of
DateTime dob = Convert.ToDateTime(d.ToString());
If you are entering string in dd/MM/yyyy then use below code else change accordingly.
DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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 !
 DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy", null);
Janardan Pandey at 16-Mar-12 3:36am
but please input 17/12/1984 and check it.
member60 at 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
Your Filters
0 Shai Vashdi 319
1 OriginalGriff 280
2 Sergey Alexandrovich Kryukov 250
3 Peter Leow 171
4 Abhinav S 168
0 Sergey Alexandrovich Kryukov 8,944
1 OriginalGriff 5,280
2 Peter Leow 3,985
3 Maciej Los 3,535
4 Abhinav S 3,218

Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 14 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid