How can I take two-digit and four-digit years with one call to DateTime.ParseExact?

I call .NET DateTime.ParseExact using a custom format string in the lines "MM/dd/yyyy h:mmt" . This line processes four-digit years, but not two-digit years. Is there a way to handle both cases in the same ParseExact call? I tried "MM/dd/yy h:mmt" and it only handles the two-digit case.

+6
source share
4 answers

You can pass an array of format strings for the second parameter with this overload of ParseExact - this will include both 2 and 4 year old options.

 DateTime.ParseExact(myDateTime, new []{"MM/dd/yy h:mmt", "MM/dd/yyyy h:mmt"}, CultureInfo.InvariantCulture, DateTimeStyles.None) 
+19
source

Call the DateTime.ParseExact overload, which takes 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 to the current user culture; pass DateTimeFormatInfo.InvariantInfo if your date string is always in US format.

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

See documentation MSDN documentation .

+3
source

Use the overloaded DateTime.ParseExact , which accepts 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); 
+1
source

You can always 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); 
0
source

Source: https://habr.com/ru/post/912051/


All Articles