Click here to Skip to main content
15,911,306 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i want to convert string into dateTime.
But i got the "string was not recognized as a valid datetime " this error.

My code is:
C#
string valdate = "20140525";
DateTime MyDateTime ;
MyDateTime = DateTime.ParseExact(valdate, "yyyyMMdd ",
              System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
Posted
Updated 3-Jun-14 2:28am
v2

Just add in your code :

MyDateTime=Convert.ToDateTime(valdate);
 
Share this answer
 
you have additional space "yyyyMMdd ", remove that and check
but I would use DateTime.TryParseExact Method[^] here as below. We can handle invalid user inputs without throwing an exception. :-)
C#
string valdate = "20140525";
DateTime MyDateTime ;
if(DateTime.TryParseExact(valdate, "yyyyMMdd",
              System.Globalization.CultureInfo.InvariantCulture,  System.Globalization.DateTimeStyles.None,out MyDateTime))
{
    //success and do something with MyDateTime
}
 
Share this answer
 
v4
Comments
vinodhini sekar 3-Jun-14 8:31am    
Thanks
DamithSL 3-Jun-14 8:36am    
You are welcome!
HardikPatel.SE 3-Jun-14 8:33am    
My 5+
DamithSL 3-Jun-14 8:36am    
Thank You Hardik Patel :-)
HardikPatel.SE 3-Jun-14 8:38am    
Welcome.... :)

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