Click here to Skip to main content
Rate this: bad
good
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);
            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 15-Mar-12 21:14pm
Edited 15-Mar-12 21:18pm
member6016.1K
v2
Rate this: bad
good
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);
  Permalink  
v2
Rate this: bad
good
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 !
 
try:
 DateTime dob = DateTime.ParseExact(d, "dd/MM/yyyy", null);
  Permalink  
v3
Comments
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
0 OriginalGriff 310
1 Sergey Alexandrovich Kryukov 202
2 Richard MacCutchan 160
3 PhilLenoir 154
4 Sharmanuj 146
0 Sergey Alexandrovich Kryukov 5,999
1 OriginalGriff 5,115
2 CPallini 2,473
3 Richard MacCutchan 1,597
4 Abhinav S 1,505


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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100