DateTime.TryParse all possible date types

I want to check if the date matches the correct format. There are many possibilities for valid dates like:

  • 08/02/2010
  • 2.8.2010
  • 08/02/2010 02.08
  • 02.August
  • ...

I can test each code with this code:

if (DateTime.TryParse(DateTime.ParseExact(date, "dd.M.", new CultureInfo("sl-SI")).ToString(), out dt)) 

But then I can have 40 if statements. Is it possible to check all dates with a single if statement or a single loop?

Update:

Based on the answers so far, I'm testing this code, but I have one more problem. What if I only have 9.2 not on 9.2.2010, then this code will not work:

 CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI"); string[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns(); if (DateTime.TryParseExact(date, fmts, ci, DateTimeStyles.AssumeLocal, out dt)) { DateTime = Convert.ToDateTime(date); Check = true; } 

Do I have to manually add this time or what can I do?

+7
c # datetime
source share
2 answers

You can use something like the following, but remember that more than one format can parse the same date. For example, 10/11/12 can be analyzed as yy / MM / dd or MM / dd / yy, which are valid US date formats. MM / dd / yy is more common, so it appears first in the list and is the one returned by the code below (if you use it in the US culture instead of the culture in the example).

 string testValue = "10.11.12"; DateTime result; CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI"); string[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns(); Console.WriteLine(String.Join("\r\n", fmts)); if (DateTime.TryParseExact(testValue, fmts, ci, DateTimeStyles.AssumeLocal, out result)) { Console.WriteLine(result.ToLongDateString()); } 
+8
source share

Yes ParseExact can take a list of formats for verification.

 var formats = new[] { "Mdyyyy", "dd.MM.yyyy" }; var dateValue = DateTime.ParseExact( dateString, formats, new CultureInfo("sl-SI"), DateTimeStyles.None); 
+9
source share

All Articles