7

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?

7
  • 3
    Depends on your culture, I would guess. Commented Feb 3, 2013 at 13:56
  • can you elaborate, how can this be resolved? this code is a part of backend that client from different culture in all parts of the world use Commented Feb 3, 2013 at 13:58
  • Personally, I would use one of those DateTime.Parse overloads that accept a culture and pass a fixed value. E.g. CultureInfo.InvariantCulture. Commented Feb 3, 2013 at 13:59
  • @user829174 Where does this string come from? Commented Feb 3, 2013 at 14:00
  • This code is coming from Javascript. Can you share code of how to resolve this? Commented Feb 3, 2013 at 14:00

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You need to be a careful to know the format of the input string, it varies between cultures. f.ex. "1/5/2013 11:34:28 AM" interpreted using the en-US culture results in Saturday January 5 whereas using the en-GB cutlure results in Wednesday May 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.