简体   繁体   中英

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();
     }
  }

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

You should use DateTime.ParseExact or .TryParseExact as suggested in Hans Passant's 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 , as otherwise the ParseExact method may use a culture-specific date separator (in place of /, eg "." in Germany) or time separator (in place of ":").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM