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
相关产品推荐
相关产品推荐

