Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET DateTime.Parse

When trying to use the parse method on the DateTime class, I get an exception thrown:

String was not recognized as a valid DateTime.

  • The string reads as "26/10/2009 8:47:39 AM" when outputted.
  • This string is obtained from a group on a match from a regex.
  • None of the strings obtained from this match group will parse to datetime.

Examples of other strings:

26/10/2009 8:47:39 AM
26/10/2009 8:00:41 AM
26/10/2009 7:48:35 AM

The weird thing is, I am sure it has worked before.

like image 514
Matthew Avatar asked Dec 08 '09 23:12

Matthew


People also ask

What does DateTime parse () do in C#?

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information. Converts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

What is ParseExact?

ParseExact(String, String, IFormatProvider, DateTimeStyles) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style.

How do you check if the date is in dd mm yyyy format in C#?

Use the DateTime. TryParseExact method in C# for Date Format validation. They method converts the specified string representation of a date and time to its DateTime equivalent. It checks whether the entered date format is correct or not.


2 Answers

Parsing strings into DateTime object is almost always a pain. If you know for certain that they will always have the format as your examples do, this should work:

string input = "26/10/2009 8:00:41 AM";
DateTime dateTime = DateTime.ParseExact(input, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
like image 163
Fredrik Mörk Avatar answered Nov 15 '22 19:11

Fredrik Mörk


Parse takes regional settings (culture of current thread) into account. Therefore, I'd use ParseExact and specify the correct format explicitly with an invariant culture (or the culture you need, eg. en-US, for AM/PM).

like image 31
Lucero Avatar answered Nov 15 '22 19:11

Lucero