How do I convert an Excel serial date number to a .NET DateTime?

Viewed 83562

How do I convert from excel serial date to a .NET date time?

For example 39938 is 05/05/2009.

4 Answers

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.

Related