How do I convert an Excel serial date number to a .NET DateTime?
Where 39938 is the number of days since 1/1/1900?
In that case, use the framework library function DateTime.FromOADate()
.
This function encapsulates all the specifics, and does bounds checking.
For its historical value, here is a possible implementation:
(C#)
public static DateTime FromExcelSerialDate(int SerialDate)
{
if (SerialDate > 59) SerialDate -= 1; //Excel/Lotus 2/29/1900 bug
return new DateTime(1899, 12, 31).AddDays(SerialDate);
}
VB
Public Shared Function FromExcelSerialDate(ByVal SerialDate As Integer) As DateTime
If SerialDate > 59 Then SerialDate -= 1 ' Excel/Lotus 2/29/1900 bug
Return New DateTime(1899, 12, 31).AddDays(SerialDate)
End Function
[Update]:
Hmm... A quick test of that shows it's actually two days off. Not sure where the difference is.
Okay: problem fixed now. See the comments for details.
For 39938 do this: 39938 * 864000000000 + 599264352000000000
864000000000 represents number of ticks in a day 599264352000000000 represents number of ticks from the year 0001 to the year 1900
I find it simpler using FromOADate method, for example:
DateTime dt = DateTime.FromOADate(39938);
Using this code dt is "05/05/2009".