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

ASP.NET Core中如何将TimeSpan转换为不含天数的格式?

解决TimeSpan超过一天时转成总小时数的hh:mm:ss格式问题

核心思路是将TimeSpan的天数转换为小时数,合并到总小时数中,再搭配原有的分钟、秒进行格式化。

C# 实现示例

直接计算总小时数并格式化:

TimeSpan targetSpan = new TimeSpan(1, 6, 0, 0); // 对应输入的1.6:00:00
string result = $"{(int)targetSpan.TotalHours:D2}:{targetSpan.Minutes:D2}:{targetSpan.Seconds:D2}";
// 输出结果:30:00:00

如果需要处理包含毫秒的场景,可调整格式:

string resultWithMs = $"{(int)targetSpan.TotalHours:D2}:{targetSpan.Minutes:D2}:{targetSpan.Seconds:D2}.{targetSpan.Milliseconds:D3}";

也可以封装成通用方法方便复用:

public static string FormatTimeSpanToTotalHourFormat(TimeSpan timeSpan)
{
    return $"{(int)timeSpan.TotalHours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
}

说明:

  • TotalHours 属性会返回包含天数转换后的总小时数(如1天6小时对应30.0),取整数部分即可得到总小时数
  • D2 格式符用于确保数值不足两位时自动补零,保持hh:mm:ss的统一格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 15:55:53