C # parsing a string of any date format in datetime

In C #, how to handle a string of the format "dd/mm/yyyy" or format "dd-mm-yyyy" in datetime? I get an error that says my string is not in the correct format. I need to be able to analyze all formats, not just one of them.

+8
c # datetime parsing
source share
4 answers

mm means minute, uppercase mm means month.

In addition, you should use CultureInfo.InvariantCulture if you want to parse strings with / as a date separator, since this is a char replacement for your current culture date separator:

So this works:

 DateTime.ParseExact("23/07/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture); 

See: "/" Specifier for Special Format

+8
source share

You can define any format you want - plus you can get a list of default values ​​for a given culture.

 var ci = new CultureInfo("en-US"); var formats = new[] { "Md-yyyy", "dd-MM-yyyy", "MM-dd-yyyy", "Mdyyyy", "dd.MM.yyyy", "MM.dd.yyyy" } .Union(ci.DateTimeFormat.GetAllDateTimePatterns()).ToArray(); DateTime.ParseExact("07/23/2013", formats, ci, DateTimeStyles.AssumeLocal).Dump(); DateTime.ParseExact("07-23-2013", formats, ci, DateTimeStyles.AssumeLocal).Dump(); DateTime.ParseExact("23-07-2013", formats, ci, DateTimeStyles.AssumeLocal).Dump(); DateTime.ParseExact("23.07.2013", formats, ci, DateTimeStyles.AssumeLocal).Dump(); 

Output:

 7/23/2013 12:00:00 AM 7/23/2013 12:00:00 AM 7/23/2013 12:00:00 AM 7/23/2013 12:00:00 AM 
+8
source share

You need to determine which date formats you want to accept. There are no such things as all formats. Once you determine that you can pass an array of format to DateTime.ParseExact

Your code might look like this:

 string[] formats = new string[2] {"dd/MM/yyyy", "dd-MM-yyyy"}; string date = "23-02-2013"; try { DateTime result = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal); } catch (FormatException) { // your error handling code here } 
+3
source share

You can use the DateTime.ParseExact method with any given format.

  var d = DateTime.ParseExact(token, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal); 
+1
source share

All Articles