How do I convert from excel serial date to a .NET date time?
For example 39938 is 05/05/2009.
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)
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.
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.
I find it simpler using FromOADate method, for example:
DateTime dt = DateTime.FromOADate(39938);
Using this code dt is "05/05/2009".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With