对于时间进行排序的方法最常见的就是:在保证需要进行比较的时间compareTime不为空的情况下,直接使用new Date(compareTime).getTime()获取时间戳进行比较大小即可,但是对于HH:MM:SS这种new Date()不支持的时间格式我们该如何比较呢?有下面三种方法:
1.将时间转换为总秒数
将HH:MM:SS格式的时间转换为总秒数,然后比较总秒数的大小。例如,将HH:MM:SS格式的时间转换为秒数的公式为:总秒数 = (HH * 3600) + (MM * 60) + SS。然后比较两个时间的总秒数大小。
function compareTime(time1, time2) {
// 将时间字符串分割成小时、分钟、秒
const [h1, m1, s1] = time1.split(':').map(Number);
const [h2, m2, s2] = time2.split(':').map(Number);
// 将时间转换为总秒数
const totalSeconds1 = h1 * 3600 + m1 * 60 + s1;
const totalSeconds2 = h2 * 3600 + m2 * 60 + s2;
// 比较总秒数的大小
if (totalSeconds1 < totalSeconds2) {
return -1;
} else if (totalSeconds1 > totalSeconds2) {
return 1;
} else {
return 0;
}
}
// 示例
console.log(compareTime('12:30:15', '10:25:30')); // 1
console.log(compareTime('12:30:15', '12:30:15')); // 0
console.log(compareTime('12:30:15', '15:40:10')); // -1
2.使用Date对象
将HH:MM:SS格式的时间转换为Date对象,然后比较两个Date对象的大小。例如,可以将时间字符串转换为Date对象,然后使用Date对象的比较方法(如getTime())进行比较。
function compareTimeUsingDate(time1, time2) {
// 创建Date对象 其中2000-01-01可以更换成其它的,只要保证比较的时间日期是一致的就行
const date1 = new Date(`2000-01-01T${time1}`);
const date2 = new Date(`2000-01-01T${time2}`);
// 比较Date对象
if (date1 < date2) {
return -1;
} else if (date1 > date2) {
return 1;
} else {
return 0;
}
}
// 示例
console.log(compareTimeUsingDate('12:30:15', '10:25:30')); // 1
console.log(compareTimeUsingDate('12:30:15', '12:30:15')); // 0
console.log(compareTimeUsingDate('12:30:15', '15:40:10')); // -1
3.分割时间字符串
将HH:MM:SS格式的时间字符串按照":"分割成小时、分钟、秒三个部分,然后逐个比较小时、分钟、秒的大小。
function compareTimeByParts(time1, time2) {
const [h1, m1, s1] = time1.split(':').map(Number);
const [h2, m2, s2] = time2.split(':').map(Number);
if (h1 < h2) {
return -1;
} else if (h1 > h2) {
return 1;
} else {
if (m1 < m2) {
return -1;
} else if (m1 > m2) {
return 1;
} else {
if (s1 < s2) {
return -1;
} else if (s1 > s2) {
return 1;
} else {
return 0;
}
}
}
}
// 示例
console.log(compareTimeByParts('12:30:15', '10:25:30')); // 1
console.log(compareTimeByParts('12:30:15', '12:30:15')); // 0
console.log(compareTimeByParts('12:30:15', '15:40:10')); // -1
4.时间戳比较法
先将两个时间字符串转换成对应的时间戳,然后比较两个时间戳的大小。这种方法能够避免时间字符串格式不规范的问题,但需要额外的时间戳转换操作。
function compareTime(time1, time2) {
var d1 = new Date("1970-01-01T" + time1 + "Z");
var d2 = new Date("1970-01-01T" + time2 + "Z");
var timestamp1 = d1.getTime();
var timestamp2 = d2.getTime();
if (timestamp1 > timestamp2) {
return 1;
} else if (timestamp1 < timestamp2) {
return -1;
} else {
return 0;
}
}
// 示例用法
var time1 = "10:30:00";
var time2 = "12:15:30";
var result = compareTime(time1, time2);
if (result === 1) {
console.log(time1 + "晚于" + time2);
} else if (result === -1) {
console.log(time1 + "早于" + time2);
} else {
console.log(time1 + "等于" + time2);
}