开发者

Convert to DateTime from string containing decimal and comma millisecond separators

开发者 https://www.devze.com 2023-04-10 06:52 出处:网络
Given the following 2 strings notice the \".185\" and \",185\" 2011-09-15 17:05:37,185 2011-09-15 17:05:37.185

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();
 开发者_JS百科    }
  }


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 /, e.g. "." in Germany) or time separator (in place of ":").

0

精彩评论

暂无评论...
验证码 换一张
取 消