Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Parse throws exception when parsing string

Tags:

c#

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?

like image 418
user829174 Avatar asked Feb 03 '13 13:02

user829174


People also ask

What is DateTime parse exception?

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.

How to Parse DateTime string in c#?

' 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.

How does DateTime TryParse work?

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.


1 Answers

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.

like image 132
manojlds Avatar answered Nov 15 '22 10:11

manojlds