如何将今天的时间和日期与用户选择的日期进行比较。如果用户选择今天的日期或明天的日期,并且时间是下午 2 点或下午 2 点以上,那么我应该显示警报,说明交货时间已结束。
我尝试过这样的事情
$scope.checkDateTime=function(){
angular.forEach($scope.orders.start_date,function(s){
console.log(s);
var curTime = moment().format('YYYY-MM-DD HH:mm:ss');
var orderTime = s+' 14:00:00';
console.log(moment(orderTime).diff(curTime,'seconds'));
if(moment(orderTime).diff(curTime,'seconds')>86400) {
console.log('hooray!')
}
})
}
我有 orders.start_date
是 ng-repeat 内的输入字段,所以我使用 forEach
循环。我只想检查所选日期是今天还是明天的日期。然后我必须检查时间,如果超过下午 2 点,那么我就不应该允许。否则我可以允许。
最佳答案
我不确定可接受的订单期何时开始(因为检查这一天是今天还是明天意味着从 00:00 到 14:00 的一切都是公平的游戏),但这是一种方法基于您的代码:
$scope.checkDateTime = function(){
angular.forEach($scope.orders.start_date, function(s){
console.log(s);
var selectedTime = moment(s);
// create boundaries for time ranges
var today_end = moment("14:00","HH:mm"); // today 14:00
var today_start = moment().subtract(1,'day').endOf('day'); // end of yesterday (since we need to include 00:00 of today)
var tomorrow_end = moment("14:00","HH:mm").add(1,'day'); // tomorrow 14:00
var tomorrow_start = moment().endOf('day'); // end of today (since we need to include 00:00 of tomorrow)
// check if time in questions fits any of the ranges
if( ( selectedTime.isBetween(today_start, today_end) ||
( selectedTime.isBetween(tomorrow_start, tomorrow_end) )
console.log('hooray!')
}
})
}
请注意,isBetween(t1, t2)
不将 t1
和 t2
包含在可接受的范围内。
关于使用 Moment.js 检查所选日期是今天的日期且时间是下午 2 点的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40243375/