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

如何在C#中将SQL的BIGINT类型时间戳转换为指定格式日期时间

转换方案

你遇到的BIGINT时间值不属于Unix时间戳范畴,是按时间分量固定顺序拼接的定长数值,格式为yyyyMMddHHmmssfff,从左到右依次为4位年份、2位月份、2位日期、2位小时、2位分钟、2位秒、3位毫秒,总长度17位,和你给出的示例20220504112601755结构完全匹配,直接按位截取解析即可,不需要做纪元时间的偏移换算。

实现步骤

  • 将BIGINT数值转为固定17位长度的字符串,长度不足时在头部补0,避免月初、凌晨等场景下前导零丢失导致解析错位
  • 按固定索引位置截取各时间分量,转为整数类型
  • 用截取到的分量构造DateTime对象
  • 调用ToString()方法按要求的格式输出字符串

可直接运行的代码示例

using System;

public class TimeConverter
{
    public static DateTime ConvertFromSqlBigInt(long sqlBigIntTime)
    {
        // 转为17位定长字符串,前补0兼容所有合法时间值
        string timeStr = sqlBigIntTime.ToString().PadLeft(17, '0');
        
        // 按固定位截取各时间分量
        int year = int.Parse(timeStr.Substring(0, 4));
        int month = int.Parse(timeStr.Substring(4, 2));
        int day = int.Parse(timeStr.Substring(6, 2));
        int hour = int.Parse(timeStr.Substring(8, 2));
        int minute = int.Parse(timeStr.Substring(10, 2));
        int second = int.Parse(timeStr.Substring(12, 2));
        int millisecond = int.Parse(timeStr.Substring(14, 3));

        // 如果数据库存储的是UTC时间,构造时传入DateTimeKind.Utc即可
        return new DateTime(year, month, day, hour, minute, second, millisecond);
    }

    public static void Main()
    {
        long sourceValue = 20220504112601755;
        DateTime targetTime = ConvertFromSqlBigInt(sourceValue);
        // 按要求格式输出,结果为 2022.05.04 11:26:01
        string output = targetTime.ToString("yyyy.MM.dd HH:mm:ss");
        Console.WriteLine(output);
    }
}

边界情况说明

  • 如果业务场景中存储的BIGINT值不带最后3位毫秒(总长度14位,精确到秒),将补零长度改为14,删除毫秒截取逻辑即可
  • 不建议用数值除法、取模的方式拆分时间分量,这类写法在遇到月份为1月、小时为0点等存在前导零的场景时,很容易出现分量计算错位,字符串截取方案容错性更高
  • 若数据库存储的是UTC标准时间,构造DateTime时请指定DateTimeKind.Utc,需要本地时间时再调用ToLocalTime()方法转换,避免时区偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 22:57:25