Converting a string to a DateTime with more than 7 decimals of milliseconds

前端 未结 2 557
终归单人心
终归单人心 2021-01-20 05:17

So I am trying to convert a string date in the following format to a DateTime. I am able to parse it using ParseExact when there are 7 decimals of fractions of a second usin

相关标签:
2条回答
  • 2021-01-20 05:50

    I don't believe you can do this with the normal parsing code and the existing text. DateTime's precision only goes down to ticks, where a tick is 100 nanoseconds. I think the simplest thing to do is truncate the string itself:

    string pattern = "yyyy-MM-dd HH:mm:ss.fffffff";
    if (text.Length > pattern.Length)
    {
        text = text.Substring(0, pattern.Length);
    }
    DateTime value = DateTime.ParseExact(text, pattern, CultureInfo.InvariantCulture);
    

    Obligatory plug: in Noda Time 2.0 you won't need to do this as it supports a precision of nanoseconds :)

    0 讨论(0)
  • 2021-01-20 05:50

    To addition Jon's answer, 7 is the limit for parsing and represent significant digits of the seconds fraction.

    From The "fffffff" custom format specifier

    Although it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On the Windows NT 3.5 (and later) and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.

    0 讨论(0)
提交回复
热议问题