Click here to Skip to main content
14,387,302 members
Rate this:
Please Sign up or sign in to vote.
See more:
employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim()).ToString();


throwing an exception ie,

String was not recognized as a valid DateTime.
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 2

I'd suggest to use DateTime.TryParse[^] method instead of Convert.ToDateTime. MSDN mention: "(it) converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded".
   
Comments
Manas Bhardwaj 18-Nov-14 14:16pm
   
Yes +5!
Maciej Los 18-Nov-14 14:18pm
   
Thank you, Manas ;)
Rate this:
Please Sign up or sign in to vote.

Solution 3

issue is in Convert.ToDateTime(txtDateOfBirth.Text.Trim())
if you know the date time format, try with DateTime.ParseExact or DateTime.TryParseExact
DateTime dt = DateTime.ParseExact(txtDateOfBirth.Text.Trim(), "MM/dd/yyyy", null);
//if the date format is MM/dd/yyyy 
// sample date 19/11/2014
   
v2
Comments
Manas Bhardwaj 18-Nov-14 14:16pm
   
Yup +5!
Rate this:
Please Sign up or sign in to vote.

Solution 4

You could do something like this:

http://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx[^]

DateTime dateValue;

if (DateTime.TryParse(txtDateOfBirth.Text.Trim(), out dateValue))
{
      employee.DateOfBirth = dateValue.ToString();
}
else
{
      //Can not parse the given date
}


However, what I do not understand that you parse a string to date and then convert it again to string. You might want to think about it.
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

Remove the ToString from the end:
employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim());
   

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




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