jump to navigation

Convertir Fechas de Excel a Date en C# 11 junio, 2007

Posted by haegeth in Visual Studio.NET.
3 comments

Excel ve las fechas como un numero entero que representa el numero de dias que han pasado desde el 1-Enero-1900, asi por ejemplo 37477 equivale al 9-Agosto-2002.

Mi investigacion surge apartir de que en mi trabajo necesito traducir las fechas que arroja excel cuando exporto un archivo en formato CSV(Comma Separated Values) a una aplicación hecha en C.

Éste es el código que encontré y me ha resultado sumamente útil, luego les pongo el código para traducir las horas.

    public void ExcelSerialDateToDMY(int nSerialDate, ref int nDay, ref int nMonth, ref int nYear)
{
// Excel/Lotus 123 have a bug with 29-02-1900. 1900 is not a
// leap year, but Excel/Lotus 123 think it is…
if (nSerialDate == 60)
{
nDay    = 29;
nMonth    = 2;
nYear    = 1900;

return;
}
else if (nSerialDate < 60)
{
// Because of the 29-02-1900 bug, any serial date
// under 60 is one off… Compensate.
nSerialDate++;
}

// Modified Julian to DMY calculation with an addition of 2415019
int l = nSerialDate + 68569 + 2415019;
int n = (int)(( 4 * l ) / 146097);
l = l – (int)(( 146097 * n + 3 ) / 4);
int i = (int)(( 4000 * ( l + 1 ) ) / 1461001);
l = l – (int)(( 1461 * i ) / 4) + 31;
int j = (int)(( 80 * l ) / 2447);
nDay = l – (int)(( 2447 * j ) / 80);
l = (int)(j / 11);
nMonth = j + 2 – ( 12 * l );
nYear = 100 * ( n – 49 ) + i + l;
}

public int DMYToExcelSerialDate(int nDay, int nMonth, int nYear)
{
// Excel/Lotus 123 have a bug with 29-02-1900. 1900 is not a
// leap year, but Excel/Lotus 123 think it is…
if (nDay == 29 && nMonth == 02 && nYear==1900)
return 60;

// DMY to Modified Julian calculatie with an extra substraction of 2415019.
long nSerialDate =
(int)(( 1461 * ( nYear + 4800 + (int)(( nMonth – 14 ) / 12) ) ) / 4) +
(int)(( 367 * ( nMonth – 2 – 12 * ( ( nMonth – 14 ) / 12 ) ) ) / 12) –
(int)((3 * ((int)((nYear + 4900 + (int)((nMonth – 14) / 12)) / 100))) / 4) +
nDay – 2415019 – 32075;

if (nSerialDate < 60)
{
// Because of the 29-02-1900 bug, any serial date
// under 60 is one off… Compensate.
nSerialDate–;
}

return (int)nSerialDate;
}