我需要比较字符串类型的两个时间值。它可能是以下格式,
=6:12>7:12 => False
=6:12 PM >7:12 AM => True
= 4/19/2017 6:12 PM > 4/19/2017 7:12 AM => True
像Excel一样。
您能否建议我,如何使用 JS 实现我的场景
最佳答案
Javascript 没有原生方法来处理时间,因此您需要创建自己的函数来将时间戳转换为可以比较的单位,在本例中我使用秒,但您可以使用毫秒。
您还显示了一个日期戳,您可以使用 Date
对象将时间戳转换为可以比较的毫秒。
const timeToSeconds = s => {
const m = s.match(/(\d{1,2})\:(\d{2})\s*(AM|PM)*/)
return (
(parseInt(m[1]) * 60) +
(parseInt(m[2])) +
(m[3] === 'PM' ? 12 * 60 : 0)
)
}
console.log(
timeToSeconds('6:12') > timeToSeconds('7:12')
)
console.log(
timeToSeconds('6:12 PM') > timeToSeconds('7:12 AM')
)
console.log(
new Date('4/19/2017 6:12 PM').getTime() > new Date('4/19/2017 7:12 PM').getTime()
)
关于javascript - 如何使用js比较所有格式的两个时间值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43496702/