Reputation: 1256
string createddate = "10/14/2016 11:46 AM";
DateTime date = Convert.ToDateTime(createddate);
I am trying to convert string as a datetime format it is working some devices, some devices throwing above exception. whys ? please help me to resolve this issue.
Upvotes: 0
Views: 1603
Reputation: 35290
The problem is that each device will potentially have a different culture. You can ignore the culture and force it to recognize a specific date format in your string:
DateTime date = DateTime.ParseExact(
createddate , "MM/dd/yy HH:mm tt", CultureInfo.InvariantCulture);
See MSDN for standard date string formats and custom date string formats.
Upvotes: 2
Reputation: 45243
You need to define the date and time format when you convert a string
to a DateTime
value. Guessing the default format or hoping the format is correct will lead to diffent kind of bugs. That's one of the most common sources of the bugs which can't be reproduced on the developer's machine.
Example to do it right:
var date = DateTime.ParseExact("10/14/2016 11:46 AM",
"MM/dd/yyyy HH:mm tt",
CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 298
Try this:
string createddate = "10/14/2016 11:46 AM";
DateTime dateTime;
DateTime.TryParse(createddate, out dateTime);
Upvotes: 0