c# - 将 double 转换为日期时间?

标签 c# excel datetime datetime-format

我有一个 .CSV 文件,我正在将其读入 C# 程序。在其中一列中,有一个日期,但它是“通用”格式,因此它在 .CSV 中显示为数字。例如:41172。

如何在 C# 中将此数字转换为格式为 dd/mm/yyyy 的日期? 41172 相当于 2012 年 9 月 20 日。

最佳答案

要从“Excel 格式”的日期时间转换为 C# 日期时间,您可以使用 DateTime.FromOADate功能。

在你上面的例子中:

   DateTime myDate = DateTime.FromOADate(41172);

要以所需格式写出显示,请使用:

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

如果您想知道 Excel 日期处理中的差异从何而来,那应该是故意的:

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.

来源:http://www.ozgrid.com/Excel/ExcelDateandTimes.htm

关于c# - 将 double 转换为日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968570/

相关文章:

c# - 如何修复2019版中的Unity编译器错误?

javascript - 如何在 ASP.NET MVC 中的存储库上执行函数?

VBA 宏计算分钟

arrays - 如何使用 VBA 循环遍历多个数组?

mysql - 如何使用特定格式插入当前日期时间

c# - 正则表达式和平衡组

c# - OData 返回 'Cannot find the services container for route ' odata-Unversioned'

php - 用不同的值更新现有表,PHP?

mysql - ActiveRecord 仅查找每小时记录

python - 动画不适用于日期时间 X 值,但适用于整数