Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For example 39938 is 05/05/2009.

like image 642
David Basarab Avatar asked Apr 07 '09 20:04

David Basarab


People also ask

How do I convert serial number date to time in Excel?

Select the cells that have the number that you want to convert into a date. Click the 'Home' tab. In the 'Number' group, click on the Number Formatting drop-down. In the drop-down, select 'Long Date' or Short Date' option (based on what format would you want these numbers to be in)

How do you convert a number into a date format?

For this, simply pick Date in the Number Format box on the Home tab. To apply a format other than default, then select the cells with serial numbers and press Ctrl+1 to open the Format Cells dialog. On the Number tab, choose Date, select the desired date format under Type and click OK.

How do I change a 5 digit number to a date in Excel?

Select a blank cell (says cell B2) adjacent to the serial number cell you need to convert to date, then enter formula =TEXT(A2,"m/d/yyyy") into the Formula Bar, and press the Enter key. 2. Keep selecting cell B2, then drag its Fill Handle to the cell with the serial number you need to convert to date.


2 Answers

I find it simpler using FromOADate method, for example:

DateTime dt = DateTime.FromOADate(39938); 

Using this code dt is "05/05/2009".

like image 172
Narcís Calvet Avatar answered Oct 13 '22 20:10

Narcís Calvet


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.

like image 43
Joel Coehoorn Avatar answered Oct 13 '22 21:10

Joel Coehoorn