我正在尝试与预定时间匹配当前时间,但我陷入了匹配,因为那些是在字符串中。 这是我的代码
$scope.TimeString = "17:00-21:00,7:00-10:00,9:45-12:00";
$scope.currentTime = $filter('date')(new Date(), 'HH:mm');
$scope.IsItemAvailable = function (timeString) {
var tempTimeArray = "";
tempTimeArray = timeString.split(",");
for (var i = 0; i < tempTimeArray.length; i++) {
var tempTime = tempTimeArray[i];
var itemTime = tempTime.split("-")
var fromTime = $filter('date')(itemTime[0], 'HH:mm');
var toTime = $filter('date')(itemTime[1], 'HH:mm');
if ($scope.currentTime >= fromTime && $scope.currentTime <= toTime) {
$scope.isAvailable = true;
break;
}
else {
$scope.isAvailable = false;
}
}
it's returning false always.Any please help me to acheive it.
答案 0 :(得分:0)
如果您可以将时间转换为零填充:09:55
,那么您可以将其作为字符串进行比较(如果您没有午夜时间间隔)。
否则,您可以将hh:mm
转换为分钟数,然后进行比较:
var cur = $scope.currentTime.split(':');
var from = itemTime[0].split(':');
var to = itemTime[1].split(':');
cur = cur[0]*60+ cur[1];
from = from[0]*60+from[1];
to = to[0]*60+ to[1];
if (cur >= from && cur <= to) {
// available
}
一些DRY解决了:
var times = [$scope.currentTime, itemTime[0], itemTime[1]];
times.map(interval => interval.split(':'))
.map(interval => interval[0]*60 + interval[1]);
if (times[0] >= times[1] && times[0] <= times[2]) {
// available
}