When trying to use the parse method on the DateTime
class, I get an exception thrown:
String was not recognized as a valid DateTime.
"26/10/2009 8:47:39 AM"
when outputted.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.
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.
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.
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.
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);
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).
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