如何检查"HH:mm:ss"的时间是上午还是下午?



我有一个时间数组。

let data = ["09:00:00", "09:10:00", "09:20:00", "09:30:00", "09:40:00", "09:50:00", "10:00:00", "10:10:00", "10:20:00", "10:30:00", "10:40:00", "10:50:00", "11:00:00", "11:10:00", "11:20:00", "11:30:00", "11:40:00", "11:50:00", "12:00:00", "12:10:00", "12:20:00", "12:30:00", "12:40:00", "12:50:00", "13:00:00", "13:10:00", "13:20:00", "13:30:00", "13:40:00", "13:50:00", "14:00:00", "14:10:00", "14:20:00", "14:30:00", "14:40:00", "14:50:00", "15:00:00", "15:10:00", "15:20:00", "15:30:00", "15:40:00", "15:50:00"]

如何使用javascript检查每次是上午还是下午?

:拆分字符串。将第一部分转换为数字,然后与12:进行比较

let data = ["09:00:00", "09:10:00", "09:20:00", "09:30:00", "09:40:00", "09:50:00", "10:00:00", "10:10:00", "10:20:00", "10:30:00", "10:40:00", "10:50:00", "11:00:00", "11:10:00", "11:20:00", "11:30:00", "11:40:00", "11:50:00", "12:00:00", "12:10:00", "12:20:00", "12:30:00", "12:40:00", "12:50:00", "13:00:00", "13:10:00", "13:20:00", "13:30:00", "13:40:00", "13:50:00", "14:00:00", "14:10:00", "14:20:00", "14:30:00", "14:40:00", "14:50:00", "15:00:00", "15:10:00", "15:20:00", "15:30:00", "15:40:00", "15:50:00"];
function checkAMorPM(time) {
var hrs = Number(time.split(":")[0]);
return (hrs >= 12 ? "PM" : "AM");
}
for(var i = 0; i < data.length; i++) {
console.log(`${data[i]}: ${checkAMorPM(data[i])}`);
}

或者,如果你愿意,你可以在一行中完成:

const checkAMorPM = time => +time.split(':')[0] < 12 ? "AM" : "PM";

不要担心拆分值-只需使用parseInt((将其转换为数字-这只会将值(最多为第一个非数字值(转换为一个数字,然后可以根据12进行检查。

因此,因为他的性格":"对于整数无效-只有前两个字符将被解析-这意味着";09:00:00";将被视为其";09〃;并且被解析为整数9,并且当与12进行比较时;AM";。

let data = ["09:00:00", "09:10:00", "09:20:00", "09:30:00", "09:40:00", "09:50:00", "10:00:00", "10:10:00", "10:20:00", "10:30:00", "10:40:00", "10:50:00", "11:00:00", "11:10:00", "11:20:00", "11:30:00", "11:40:00", "11:50:00", "12:00:00", "12:10:00", "12:20:00", "12:30:00", "12:40:00", "12:50:00", "13:00:00", "13:10:00", "13:20:00", "13:30:00", "13:40:00", "13:50:00", "14:00:00", "14:10:00", "14:20:00", "14:30:00", "14:40:00", "14:50:00", "15:00:00", "15:10:00", "15:20:00", "15:30:00", "15:40:00", "15:50:00"];

data.forEach(function(item){
parseInt(item, 10) < 12 
? console.log('AM')
: console.log('PM')
})

相关内容

  • 没有找到相关文章

最新更新