Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a .CSV file which I am reading into a C# program. In one of the columns, there is a date, but it is in the "general" format, so it shows up in the .CSV as a number. For example: 41172.

How can I convert this number to a date with format dd/mm/yyyy in C#? 41172 is equivalent to 20/09/2012.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

To go from an DateTime in the "Excel Format" to a C# Date Time you can use the DateTime.FromOADate function.

In your example above:

   DateTime myDate = DateTime.FromOADate(41172);

To write it out for display in the desired format, use:

   myDate.ToString("dd/MM/yyyy");

If you are wondering where the discrepancies in Excel's date handling come from, it's supposed to be on purpose:

When Lotus 1-2-3 was first released, the program assumed that the year 1900 was a leap year even though it actually was not a leap year. This made it easier for the program to handle leap years and caused no harm to almost all date calculations in Lotus 1-2-3.

When Microsoft Multiplan and Microsoft Excel were released, they also assumed that 1900 was a leap year. This allowed Microsoft Multiplan and Microsoft Excel to use the same serial date system used by Lotus 1-2-3 and provide greater compatibility with Lotus 1-2-3. Treating 1900 as a leap year also made it easier for users to move worksheets from one program to the other.

Although it is technically possible to correct this behavior so that current versions of Microsoft Excel do not assume that 1900 is a leap year, the disadvantages of doing so outweigh the advantages.

Source: http://www.ozgrid.com/Excel/ExcelDateandTimes.htm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...