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

后端 未结 5 1405
-上瘾入骨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:41

    Looks like you're using the old OLE Automation date. Use

    DateTime.FromOADate(myDouble)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 23:54

    Try something like this:-

    double d = 40880.051388 ;
    DateTime dt = DateTime.FromOADate(d);
    
    0 讨论(0)
  • 2021-01-01 23:55

    Try using var dateTime = DateTime.FromOADate(40880.051388);.

    If you need to format it to a string, use dateTime.ToString("M/d/yyyy H:mm", CultureInfo.InvariantCulture) for that. That will give you 24-hour string (change H to h for a 12-hour system).

    If you need greater precision (by a factor 1000 or more) than offered by FromOADate, see my answer in another thread.

    0 讨论(0)
  • 2021-01-01 23:56

    The value is an offset in days from December 30th, 1899. So you want:

    new DateTime(1899, 12, 30).AddDays(40880.051388)
    
    0 讨论(0)
提交回复
热议问题