Convert to DateTime from a string containing decimal and comma millisecond delimiters

Given the following 2 lines, pay attention to ".185" and ", 185"

  • 2011-09-15 17:05:37,185
  • 2011-09-15 17:05:37.185

Reading from a file (not in my control), and I see that they have dates in both formats. I need to create a function that serves both scenarios.

Is " . " And " , " culture specific?

Any suggestion for such a feature?

This below does not work as I am not getting the date.

  class Program { static void Main(string[] args) { string date1="2011-09-15 17:05:37.185"; string date2="2011-09-15 17:05:37,185"; const string format1 = "dd/MM/yyyy HH:mm:ss.ff"; const string format2 = "dd/MM/yyyy HH:mm:ss,ff"; DateTime resultDate1; DateTime resultDate2; DateTime.TryParseExact(date1, format1, CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate1); DateTime.TryParseExact(date2, format2, CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate2); Console.WriteLine(resultDate1.ToString()); Console.WriteLine(resultDate2.ToString()); Console.Read(); } } 
+4
source share
2 answers

Does it. and, specific culture?

Yes. In Europe, a comma is often used instead of a period as a decimal separator.

Any suggestion for a solution?

Yes. My first thought is that the DateTime.ParseExact () / DateTime.TryParseExact () functions have an overload that allows you to test an array of formats . You can enable both the en-US option and the en-GB option. Except that I don't think this will work, as you can still only include one culture specifier. So instead, I recommend calling .Replace () before passing the string to the ParseExact function to change any commas that may be on the string during periods.

In the updated code example, your format string just doesn't match your example dates. You should use this:

yyyy-MM-dd HH: mm: ss.fff

+8
source

You should use DateTime.ParseExact or .TryParseExact as stated in the Hans Passant comment.

 DateTime d1; string[] formats = new [] { "yyyy-MM-dd HH:mm:ss.fff", "yyyy-MM-dd HH:mm:ss,fff" }; DateTime.TryParseExact(s1, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out d1); 

You should also specify CultureInfo.InvariantCulture , because otherwise the ParseExact method can use a date separator for a specific culture (instead of /, for example, "." In Germany) or a time separator (instead of ":").

+3
source

All Articles