You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从日期时间值生成Excel常规格式等效数值

在C#中实现Excel日期到常规格式数值的转换

Excel的日期时间值在常规格式下存储为双精度浮点数:整数部分代表从基准日期开始的天数,小数部分代表一天中的时间比例。默认使用1900日期系统(基准为1899年12月31日),另有可选的1904日期系统(基准为1904年1月1日,多用于早期Mac版本)。以下是具体实现方法:

核心逻辑

  1. 1900日期系统:
    • 基准日期:1899-12-31
    • 注意Excel的历史bug:错误将1900年视为闰年,因此1900年3月1日及以后的日期,计算出的天数需要额外加1(因为Excel虚构了1900年2月29日这一天)。
  2. 1904日期系统:
    • 基准日期:1904-01-01
    • 无闰年bug,直接计算目标日期与基准日期的时间差总天数即可。

C#实现代码

public static double ConvertDateTimeToExcelSerial(DateTime dateTime, bool use1904System = false)
{
    if (use1904System)
    {
        DateTime excelBase = new DateTime(1904, 1, 1);
        TimeSpan timeDiff = dateTime - excelBase;
        return timeDiff.TotalDays;
    }
    else
    {
        DateTime excelBase = new DateTime(1899, 12, 31);
        TimeSpan timeDiff = dateTime - excelBase;
        double serialValue = timeDiff.TotalDays;
        
        // 处理1900年闰年bug:1900年3月1日及以后的日期需额外加1天
        if (dateTime >= new DateTime(1900, 3, 1) && serialValue >= 60)
        {
            serialValue += 1;
        }
        
        return serialValue;
    }
}

使用示例

针对你提供的日期2024-12-11 12:12:12 AM,调用方法:

DateTime targetDate = new DateTime(2024, 12, 11, 0, 12, 12);
double excelSerial = ConvertDateTimeToExcelSerial(targetDate);
// 输出结果:45637.0084722222

注意事项

  • 时区一致性:Excel日期不包含时区信息,确保输入的DateTime与Excel使用的时区一致(例如均为本地时间或UTC),避免时区转换导致的误差。
  • 无效日期处理:C#不允许创建1900-02-29这个不存在的日期,而Excel中该日期对应数值60,若需兼容此场景,可额外添加判断逻辑返回60。
  • 1904系统切换:如果你的Excel文档使用1904日期系统,调用方法时需传入use1904System = true。

内容的提问来源于stack exchange,提问作者JC Nunez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 17:35:11