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

如何将含天数的C# TimeSpan转为仅以时:分:秒展示的字符串?

解决方案

方法一:利用TimeSpan整数属性组合(推荐)

直接通过Days、Hours计算总小时数,结合Minutes和Seconds属性配合字符串格式化实现需求,这种方式准确且直观:

public static void Main()
{
    var ts1 = new TimeSpan(4, 14, 32, 17);      
    // 计算总小时数:天数转小时 + 剩余小时数
    int totalHours = ts1.Days * 24 + ts1.Hours;
    // 格式化字符串,确保分钟、秒为两位数字(不足补零)
    string result = $"{totalHours}:{ts1.Minutes:D2}:{ts1.Seconds:D2}";
    Console.WriteLine(result); // 输出:110:32:17
}

方法二:基于TotalHours整数部分处理

如果想使用TotalHours属性,可以取其整数部分作为总小时数,再通过剩余时长计算分钟和秒:

public static void Main()
{
    var ts1 = new TimeSpan(4, 14, 32, 17);      
    // 取总小时数的整数部分
    int totalHours = (int)Math.Floor(ts1.TotalHours);
    // 计算去掉总小时数后的剩余时长
    TimeSpan remaining = ts1 - TimeSpan.FromHours(totalHours);
    string result = $"{totalHours}:{remaining.Minutes:D2}:{remaining.Seconds:D2}";
    Console.WriteLine(result); // 输出:110:32:17
}

补充说明

  • 第一种方法更高效,直接利用TimeSpan自带的整数属性,避免浮点运算可能带来的精度问题。
  • :D2格式说明符用于确保分钟和秒始终显示为两位数字,比如分钟为5时会格式化为05。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:07:10