Reputation: 127
I have a string Date which is coming from Database I need to parse or convert that String Date in DateTime form. Sharing the data and code as of now sharing the date which is coming from DB
String Date="7/19/2010 7:34:43 AM";
// I am parsing in DateTime form by below code
Date= DateTime.Parse(Date).ToString("yyyy-MM-dd HH:mm:ss.fff");
But I am getting the error while parsing with existing code as String was not recognized as a valid DateTime. Can anyone please share some info how can I resolve this error so that I wont receive any exception
Note
Issue with my code is the date which is coming from Database is not a valid string type that's why I am getting the error string is not recognized as valid datetime
Upvotes: 0
Views: 1872
Reputation: 222522
You should do, using DateTime.ParseExact
DateTime dt = DateTime.ParseExact("7/19/2010 7:34:43 AM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 3676
Either you can use
This will allow you to specify specific formats. I prefer the TryParseExact as they provide good coding style for the casing error.
Upvotes: 0
Reputation: 3875
DateTime.ParseExact(yourstring, "yyyyMMdd_HH:mm:ss.fff", new CultureInfo("en-US"));
Will solve your issue.
For reference follow :
Upvotes: 0