user829174
user829174

Reputation: 6362

DateTime.Parse throws exception when parsing string

I have some client code that sends date in the following format "1/31/2013 11:34:28 AM";

I am trying to cast it into DateTime object

string dateRequest = "1/31/2013 11:34:28 AM";
DateTime dateTime = DateTime.Parse(dateRequest);

this throws

String was not recognized as a valid DateTime.

how can i cast it?

Upvotes: 7

Views: 249

Answers (1)

manojlds
manojlds

Reputation: 301047

You will have to use the DateTime.Parse(String, IFormatProvider) overload and specify culture-specific information ( or InvariantCulture).

DateTime.Parse("1/31/2013 11:34:28 AM", CultureInfo.InvariantCulture);

You can also create a specific culture with something like:

var cultureInfo = CultureInfo.CreateSpecificCulture("en-US");

Or use DateTime.ParseExact and specify the format string.

Upvotes: 4

Related Questions