-1

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

I would like to find an easy way to convert DateTime to Int where 01/01/1900 is 1 (which is used in Excel's xmls).

Community
  • 1
  • 1
TTT
  • 1,848
  • 2
  • 30
  • 60

2 Answers2

1

That's a built-in conversion:

int excelDays = (int)(yourDate.ToOADate());

Beware that 0 is not 1/1/1900, it is 12/31/1899. Screwy due to a shortcut taken by Lotus 123 programmers who were trying to avoid having to deal with leap year rules. 1900 wasn't a leap year. Having to be compatible with Lotus was a requirement back when Excel started, everybody used Lotus 123 back then. A good war story about this bug was written up by Joel Spolsky, the CEO of StackExchange in this blog post. Relevant part is "It's a bug in Excel!" I exclaimed.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
0

And here is my suggestion after compiling ideas from here above:

            private Nullable<int> ToInt1900ForExcel(DateTime DT)
    {
        if (DT.Ticks < 599266080000000000)//Below 1900-1-1, Excel has some problems representing dates, search it on the web.
            return null;
        if (DT.Ticks < 599317056000000000)//Excel reproduced a bug from Lotus for compatibility reasons, 29/02/1900 didn't actually exist.
            return (int)(DT.ToOADate()) - 1;
        return (int)(DT.ToOADate());
    }

or if you prefer (negative values and zero won't work fine in Excel)

           private int ToInt1900ForExcel(DateTime DT)
    {
        if (DT.Ticks < 599317056000000000)//Excel reproduced a bug from Lotus for compatibility reasons, 29/02/1900 didn't actually exist.
            return (int)(DT.ToOADate()) - 1;
        return (int)(DT.ToOADate());
    }
TTT
  • 1,848
  • 2
  • 30
  • 60