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?
Class DateTimeParseExceptionAn exception thrown when an error occurs during parsing. This exception includes the text being parsed and the error index. Implementation Requirements: This class is intended for use in a single thread.
' Use standard en-US date and time value Dim dateValue As Date Dim dateString As String = "2/16/2008 12:15:12 PM" Try dateValue = Date. Parse(dateString) Console. WriteLine("'{0}' converted to {1}.", dateString, dateValue) Catch e As FormatException Console.
TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With