我正在尝试将一系列时间与当前本地时间进行比较。但是比较这些数字对某些值来说是失败的据我所知,它并不总是失败同一时间字符串。我真的没有想法是什么原因。
function lastPassedTimeIndex() {
const d = new Date();
const nowHr = d.getHours();
const nowMin = d.getMinutes();
let lastPassedTimeIndex = 0;
const currentTimes = ['05:20', '06:57', '12:46', '15:48', '18:30', '20:02'];
for (const time of currentTimes) {
const t = time.split(':');
const printHr = parseInt(t[0], 10);
const printMin = parseInt(t[1], 10);
if ((printHr < nowHr) && (printMin < nowMin)) {
console.log(time, 'previous from now');
lastPassedTimeIndex++;
}
else if ((printHr === nowHr) && (printMin < nowMin)) {
console.log(time, 'previous from now, but hour is correct');
lastPassedTimeIndex++;
}
else if ((printHr === nowHr) && (printMin >= nowMin)) {
console.log(time, 'is upcoming or now and hour is correct');
lastPassedTimeIndex++;
}
else if ((printHr > nowHr)) {
console.log(time, 'is upcoming, hour is larger');
}
else {
console.log('I have no idea!');
}
}
console.log('LastPassedTimeIndex ', lastPassedTimeIndex);
return lastPassedTimeIndex;
}
这是我的控制台输出:
> I have no idea!
> I have no idea!
> 12:46 is upcoming, hour is larger
> 15:48 is upcoming, hour is larger
> 18:30 is upcoming, hour is larger
> 20:02 is upcoming, hour is larger
> LastPassedTimeIndex 0
答案 0 :(得分:1)
我只看到一个错误,以这种方式修复:
const printHr = parseInt(t[0], 10);
const printMin = parseInt(t[1], 10);
if ((printHr < nowHr) /* Take out what was here */) {
console.log(time, 'previous from now');
lastPassedTimeIndex++;
}
答案 1 :(得分:0)
只有当小时数相同时才需要比较分钟,或者只是比较字符串:
var time = new Date().toTimeString().slice(0, 5)
var times = ['05:20', '06:57', '12:46', '15:48', '18:30', '20:02']
console.log( time, times.findIndex(t => t >= time) - 1 )