如何在ASP.NET MVC控制器中用foreach循环计算时间列总和
ASP.NET MVC 控制器中时间字符串求和实现
问题背景
现有表包含times列,存储多条HH:mm格式的时间数据(如02:30、03:25、00:45),需计算这些时间的总和(预期结果如06:40)。已通过jQuery实现该功能,现需在ASP.NET MVC控制器中用foreach循环完善求和逻辑。
修正后的完整控制器代码
[HttpPost] public ActionResult getTimeSheetByBasit(DateTime? CurrentDate, string ActivityTime) { VM_TimeSheet ObjVM_TimeSheet = new VM_TimeSheet(); int LoggedUser = User.KEY(); string LoggedUserName = User.UserName(); string UserEmail = User.EmailID(); DateTime TimeIn, TimeOut; string TimeInn, TimeOuut, TotalTime; string totalActivityTime = "00:00"; // 存储最终时间求和结果 using (SecurenetDB SecurenetDB = new SecurenetDB()) { ObjVM_TimeSheet.TimesheetList = SecurenetDB.AD_TimeSheet .Where(x => DbFunctions.TruncateTime(x.ActivityDate.Value) == DbFunctions.TruncateTime(CurrentDate) && x.UserKEY == LoggedUser) .ToList(); TimeIn = SecurenetDB.AD_CardPunching .Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName) .Select(x => x.Time_In) .FirstOrDefault(); TimeOut = SecurenetDB.AD_CardPunching .Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName) .Select(x => x.Time_Out) .FirstOrDefault(); TimeInn = TimeIn.ToString("hh:mm tt"); TimeOuut = TimeOut.ToString("hh:mm tt"); TotalTime = SecurenetDB.AD_CardPunching .Where(x => DbFunctions.TruncateTime(x.EventDate) == DbFunctions.TruncateTime(CurrentDate) && x.UserName == LoggedUserName) .Select(x => x.TotalHours) .FirstOrDefault(); // --- 核心时间求和逻辑 --- if (!string.IsNullOrEmpty(ActivityTime)) { // 假设前端传递的ActivityTime是逗号分隔的时间集合,如"02:30,03:25,00:45" // 若实际分隔符不同,替换此处的分隔符即可 string[] timeStrings = ActivityTime.Split(','); int totalMinutes = 0; foreach (string timeStr in timeStrings) { // 解析每个时间字符串为TimeSpan,避免格式错误导致崩溃 if (TimeSpan.TryParse(timeStr.Trim(), out TimeSpan timeSpan)) { totalMinutes += (int)timeSpan.TotalMinutes; } // 可选:添加解析失败的处理逻辑,如日志记录 } // 将总分钟数转换为HH:mm格式,不足两位补零 int hours = totalMinutes / 60; int minutes = totalMinutes % 60; totalActivityTime = $"{hours:D2}:{minutes:D2}"; } // --- 求和逻辑结束 --- } return Json(new { TimeSheetData = this.RenderPartialViewToString("TimeSheetData", ObjVM_TimeSheet.TimesheetList), TimeIn = TimeInn, TimeOut = TimeOuut, TotalTime = TotalTime, TotalActivityTime = totalActivityTime // 返回计算得到的时间总和 }, JsonRequestBehavior.AllowGet); }
关键修正说明
- 修复遍历逻辑:原代码直接遍历
ActivityTime字符串的单个字符,会导致错误拼接,改为按分隔符拆分时间数组后遍历。 - 时间计算方式:用
TimeSpan处理时间间隔,累加总分钟数(避免直接操作字符串的逻辑错误),计算更精准。 - 格式标准化:将总分钟数转换为
HH:mm格式,确保输出统一(不足两位的小时/分钟自动补零)。 - 异常防护:增加空值判断和
TryParse方法,避免非法输入导致的运行时异常。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

