You need to enable JavaScript to run this app. C#中如何将TimeSpan计算的AHT时间格式转为hh:mm:ss
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将TimeSpan计算的AHT时间格式转为hh:mm:ss

问题修正方法

你当前生成带毫秒格式的核心原因是string.Format拼接字符串时,额外传入了duration.Milliseconds字段作为输出项,直接移除这部分内容即可得到纯hh:mm:ss格式的AHT值。

基础代码修改

直接在原有代码基础上删掉格式化模板里的毫秒占位符、以及对应的毫秒取值参数,修改后代码如下:

using(Db db = new Db())
{
    Chat newDTO = db.Chats.Where(x => x.ChatId == id).FirstOrDefault();
    DateTime startTime = Convert.ToDateTime(newDTO.FeedbackDateTime);
    DateTime endtime = Convert.ToDateTime(newDTO.FeedbackSharedDateTime);
    TimeSpan duration = endtime.Subtract(startTime);
    // 移除原格式化中的毫秒占位符与对应参数
    string stringAHT = string.Format("{0:D2}:{1:D2}:{2:D2}",
            24 * duration.Days + duration.Hours,
            duration.Minutes,
            duration.Seconds
            );
    newDTO.AuditorAHT = stringAHT;
    db.SaveChanges();
}

更易维护的优化写法

手动拼接TimeSpan字段容易出现参数错位、格式不统一的问题,建议直接使用TimeSpan内置的格式化能力实现相同效果:

  • 保留原有「将天数折算为累计小时数」的逻辑(如时长超过24小时时小时位显示为25、30等累计值,而非进位到天重新计算)时,先构造调整后的TimeSpan实例再格式化:
    TimeSpan adjustedDuration = new TimeSpan(duration.Days * 24 + duration.Hours, duration.Minutes, duration.Seconds);
    string stringAHT = adjustedDuration.ToString(@"hh\:mm\:ss");
    
  • 若不需要累计小时数、按常规跨天进位显示时长,可直接调用:
    string stringAHT = duration.ToString(@"hh\:mm\:ss");
    
  • 补充适配场景:如果需要将毫秒值四舍五入到整秒,避免不足1秒的时长格式化后全为00:00:00,可在计算后增加一行处理:
    // 小于1秒的时长直接归零,大于1秒的按四舍五入取整秒
    TimeSpan finalDuration = duration.TotalSeconds < 1 ? TimeSpan.Zero : new TimeSpan(0, 0, (int)Math.Round(duration.TotalSeconds));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 13:54:03