简体   繁体   English

将C#日期时间对象转换为Excel日期格式

[英]convert a C# datetime object into Excel date format

I need to convert a C# datetime object into the dreaded Excel date format: https://datapub.cdlib.org/2014/04/10/abandon-all-hope-ye-who-enter-dates-in-excel/ 我需要将C#日期时间对象转换为可怕的Excel日期格式: https : //datapub.cdlib.org/2014/04/10/abandon-all-hope-ye-who-enter-dates-in-excel/

ie number of days since 1 Jan 1900 expressed as a floating point number. 即自1900年1月1日以来的天数,以浮点数表示。

Is there any way to do it without resorting to DIY code? 有什么方法可以不用求助于DIY代码吗? I need it in order to create Excel-friendly CSV exports 我需要它以便创建Excel友好的CSV导出

Googling around I didn't find anything useful except that good blog post 谷歌搜索我没有发现任何有用的东西,除了那篇好博客文章

Excel dates use the OLE Automation date format. Excel日期使用OLE Automation日期格式。 You can retrieve it with DateTime.ToOADate 您可以使用DateTime.ToOADate检索它

OA Dates are a double whose integer part is the date offset from 30 December 1899 (ie earlier dates are negative) and fractional part is the time divided by 24. OA Date是一个双精度型,其整数部分是自1899年12月30日起的日期偏移量(即,较早的日期为负),而小数部分是时间除以24。

This type was used a lot in the COM/VB6 days. 这种类型在COM / VB6天内使用了很多。 Nowadays it's needed for Excel and when you need to call COM APIs that expect dates or variants with a date content. 如今,对于Excel以及当您需要调用带有日期内容的日期或变量的COM API时,它是必需的。

您可以使用以下方法将Excel日期转换回C#DateTime

return DateTime.FromOADate(SerialDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM