William Gross
William Gross

Reputation: 2103

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.

Upvotes: 8

Views: 4019

Answers (4)

Michael Liu
Michael Liu

Reputation: 55389

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.

Upvotes: 3

Lloyd
Lloyd

Reputation: 2942

Use the overloaded DateTime.ParseExact that takes a string array of formats.

MSDN:

string[] formats= {"MM/dd/yyyy h:mmt", "MM/dd/yy h:mmt"};


var dateTime = DateTime.ParseExact(dateString, formats, 
                                        new CultureInfo("en-US"), 
                                        DateTimeStyles.None);

Upvotes: 1

Oded
Oded

Reputation: 499002

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)

Upvotes: 22

Justin Niessner
Justin Niessner

Reputation: 245419

You could always just use the appropriate overload:

var date = DateTime.ParseExact(dateString,
                               new[] { "MM/dd/yyy h:mmt", "MM/dd/yy h:mmt" },
                               new CultureInfo("en-US"), 
                               DateTimeStyles.None);

Upvotes: 0

Related Questions