How to convert a double value to a DateTime in c#?

后端 未结 5 1425
-上瘾入骨i
-上瘾入骨i 2021-01-01 23:33

I have the value 40880.051388 and am storing it as a double, if I open Excel and paste in a cell and apply the following custom format \"m/d/yyyy h:mm\" to that

5条回答
  •  温柔的废话
    2021-01-01 23:42

    The following simple code will work

    DateTime.FromOADate(myDouble)
    

    However if performance is critical, it may not run fast enough. This operation is very processor intensive because the range of dates for the OLE Automation Date format begins on 30 December 1899 whereas DateTime begins on January 1, 0001, in the Gregorian calendar.

    FromOADate calls a DoubleDateToTicks function using myDouble as the only argument. This returns the number of ticks, and this value is used to create a new DateTime with unspecified DateTimeKind.

    The vast bulk of this work is done by the DoubleDateToTicks function in mscorlib. This includes code to throw an ArgumentException when the value of the double is NaN, and there are numerous ways in which it can be performance optimized depending on your exact needs.

提交回复
热议问题