Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to DateTime from string containing decimal and comma millisecond separators

Given the following 2 strings notice the ".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 can see they have dates in both formats. I need to create a function that cater for both scenarios.

Is the '.' and ',' a culture specific?

Any suggestion for such a function?

This below is not working as I don't get a 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();
     }
  }
like image 502
user9969 Avatar asked Dec 21 '22 08:12

user9969


1 Answers

Is the . and , a culture specific?

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

Any suggestion for a solution?

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

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

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

like image 53
Joel Coehoorn Avatar answered Dec 24 '22 01:12

Joel Coehoorn