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

跨午夜营业时间选择:如何为午夜后时间补加一日毫秒值

解决跨午夜营业时间的毫秒值补全问题

看起来你已经搞定了视觉上的时间列表重排,现在就差把跨午夜的时间毫秒值补上一天的时长来解决实际计算问题了。这里有几个贴合你现有代码的实用方案:


方案1:选中关闭时间时自动判断补全毫秒值

核心逻辑很简单:当用户选中关闭时间后,对比它和开门时间的原始毫秒值,如果关闭时间的msValue更小,说明是跨天的情况,直接给它加上一天的毫秒数(86400000)。你可以在指令内部或者父控制器里实现这个判断:

修改指令的选中逻辑

在你的closingTimeSync指令中,监听selectedToTime的变化,加入补全逻辑:

// 在指令的link函数里添加监听
scope.$watch('selectedToTime', function(newVal) {
  if (!newVal || !scope.selectedFromTime) return;
  
  const oneDayMs = 86400000;
  let adjustedMs = newVal.msValue;
  
  // 若关闭时间原始ms小于开门时间,说明跨天,补加一天时长
  if (adjustedMs < scope.selectedFromTime.msValue) {
    adjustedMs += oneDayMs;
  }
  
  // 存储调整后的值,用于后续时长计算或表单提交
  scope.adjustedClosingTimeMs = adjustedMs;
});

之后计算总营业时间时,直接用adjustedClosingTimeMs - scope.selectedFromTime.msValue就能得到正确结果(比如11:00am到次日2:00am,计算后就是15小时的毫秒数)。


方案2:结合现有指令逻辑,给选项添加调整后的值

你的automaticallySelectClosingTime方法已经完成了列表重排,现在可以在重排后给每个关闭时间选项自动添加adjustedMs属性,方便后续直接使用:

scope.automaticallySelectClosingTime = function(msValue) {
  scope.closingTimes = scope.availableTimes;
  var dayMS = 86400000 - 1;
  var remainingTimings = [];
  var index = scope.closingTimes.map(function(obj){return obj.msValue;}).indexOf(msValue);
  index = (index === scope.availableTimes.length-1)? 1 : index+1;
  scope.closingTimes = scope.closingTimes.slice(index,scope.availableTimes.length);
  
  if(msValue !== dayMS) {
    remainingTimings = scope.availableTimes.slice(1,index -1);
  }
  
  scope.closingTimes = scope.closingTimes.concat(remainingTimings);
  
  // 给每个选项添加调整后的毫秒值
  const oneDayMs = 86400000;
  scope.closingTimes.forEach(time => {
    time.adjustedMs = time.msValue;
    // 若当前选项的原始ms小于开门时间,补加一天
    if (time.msValue < msValue) {
      time.adjustedMs += oneDayMs;
    }
  });
  
  scope.selectedToTime = scope.closingTimes[0];
};

这样用户选中关闭时间后,直接调用scope.selectedToTime.adjustedMs就能拿到正确的跨天毫秒值,完全兼容你现有的视觉排序逻辑。


可选方案:预生成跨天时间选项(适合明确区分次日场景)

如果产品需要用户清晰看到“次日”标识,可以在生成availableTimes时额外添加一组跨天选项:

$scope.availableTimes = [];
$scope.availableTimes.push({ 'msValue': 0, 'display': '12:00 Morning' });

const oneDayMs = 86400000;
for (var msValue = 900000; msValue <= 85500000; msValue += 900000) {
  // 添加当天时间
  $scope.availableTimes.push({ 
    'msValue': msValue, 
    'display': moment(msValue).utc().format("h:mm A") 
  });
  // 添加次日时间(标注明确)
  $scope.availableTimes.push({ 
    'msValue': msValue + oneDayMs, 
    'display': `${moment(msValue).utc().format("h:mm A")} (Next Day)` 
  });
}

var dayMS = 86400000 - 1;
$scope.availableTimes.push({ 'msValue': dayMS, 'display': '12:00 Midnight' });
$scope.availableTimes.push({ 'msValue': dayMS + oneDayMs, 'display': '12:00 Midnight (Next Day)' });

这个方案会让下拉选项翻倍,适合需要明确区分“当天/次日”的场景。


推荐优先尝试方案1或方案2,改动最小且完全兼容你现有的视觉逻辑,能快速解决跨天时间的毫秒值计算问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:10