Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim()).ToString();


throwing an exception ie,

String was not recognized as a valid DateTime.
Posted

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".
 
Share this answer
 
Comments
Manas Bhardwaj 18-Nov-14 14:16pm    
Yes +5!
Maciej Los 18-Nov-14 14:18pm    
Thank you, Manas ;)
issue is in Convert.ToDateTime(txtDateOfBirth.Text.Trim())
if you know the date time format, try with DateTime.ParseExact or DateTime.TryParseExact
C#
DateTime dt = DateTime.ParseExact(txtDateOfBirth.Text.Trim(), "MM/dd/yyyy", null);
//if the date format is MM/dd/yyyy 
// sample date 19/11/2014
 
Share this answer
 
v2
Comments
Manas Bhardwaj 18-Nov-14 14:16pm    
Yup +5!
You could do something like this:

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

C#
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.
 
Share this answer
 
Remove the ToString from the end:
C#
employee.DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text.Trim());
 
Share this answer
 

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



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