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

二次信任 提交于 2019-12-18 15:25:09

问题


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 cell, I get "12/3/2011 1:14"

How can I do this parsing/Conversion in C#? I don't know if the value is milliseconds from a certain checkpoint, like epoch time, or if the value is in some specific prepared format, but how does excel come up with this particular value? Can it be done in C#?

I've tried working with TimeSpan, DateTime, and other like things in Visual Studio but am not getting anywhere.


回答1:


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

DateTime.FromOADate(myDouble)



回答2:


Try something like this:-

double d = 40880.051388 ;
DateTime dt = DateTime.FromOADate(d);



回答3:


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

new DateTime(1899, 12, 30).AddDays(40880.051388)



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/13919641/how-to-convert-a-double-value-to-a-datetime-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!