在C#中将双精度值转换为DateTime

在C#中将双精度值转换为DateTime

问题描述:

我有一个双精度值

例如:

I have a double value
Ex:

double currentDate = 20161011;  

无法将此双精度值转换为日期格式,如 10/11/2016

Unable to convert this double value into Date format like "10/11/2016"

我尝试使用

 DateTime newDate = DateTime.FromOADate(currentDate);

但通过例外情况


不是合法的OleAut日期。

Not a legal OleAut date.


您可以将double

You could convert the double to a string and then call ParseExact specifying the format.

DateTime newDate = DateTime.ParseExact(currentDate.ToString(), "yyyyMMdd", null);

但实际上您应该避免这种情况,并将日期从一开始就存储在DateTime变量中。

but really you should try to avoid this and store dates in DateTime variables from the start.