Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I accept both two-digit and four-digit years with a single call to DateTime.ParseExact?

I'm calling .NET's DateTime.ParseExact with a custom format string along the lines of "MM/dd/yyyy h:mmt". This string handles four-digit years but not two-digit years. Is there a way to handle both cases in a single ParseExact call? I've tried "MM/dd/yy h:mmt" and it only handles the two-digit case.

like image 298
William Gross Avatar asked Mar 30 '12 14:03

William Gross


People also ask

How do you parse a date in darts?

print(new DateFormat('yyyy/MM/dd'). parse(null)); That's how to parse a String to a DateTime in Dart.

What does DateTime ParseExact do?

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

What formats does DateTime parse?

Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers.


2 Answers

You can pass an array of format strings for the second parameter on this overload of ParseExact - this would include both the 2 and 4 year variants.

DateTime.ParseExact(myDateTime, 
                    new []{"MM/dd/yy h:mmt", "MM/dd/yyyy h:mmt"},
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None)
like image 140
Oded Avatar answered Feb 07 '23 10:02

Oded


Call the overload of DateTime.ParseExact that accepts an array of possible formats:

DateTime dt =
    DateTime.ParseExact(s, new[] { "MM/dd/yyyy h:mmt", "MM/dd/yy h:mmt" }, null, 0);

For the third argument, pass null or DateTimeFormatInfo.CurrentInfo if your date string is localized for the user's current culture; pass DateTimeFormatInfo.InvariantInfo if your date string is always in the U.S. format.

For the fourth argument, 0 is equivalent to DateTimeStyles.None.

See the MSDN Library documentation.

like image 23
Michael Liu Avatar answered Feb 07 '23 10:02

Michael Liu