检查 JavaScript 上的时间冲突

Check time conflict on JavaScript

我有一个注册项目,用户在列表中获取主题。现在如何检查时间是否与他人冲突?变量是字符串,我的老师只想要那种格式。

var time1 = '10:00:AM-12:00:PM';

var time2 = '10:30:AM-11:00:AM';

如何检查 time2 是否与 time1 冲突?是否有可能有用的 jquery 库?

转换 both start times and end times to dates, then check if end time of time2 is later than start time of time1 and vice versa. If both end times are later than the other's start time, you have conflicting time ranges. Converting strings to dates is easier done via moment.js.

将您的时间转换为数字并进行比较:

var time1 = '10:00:AM-12:00:PM';
var time2 = '10:30:AM-11:00:AM';
var convertedTime1 = getConvertedStartEndTime(time1)
var convertedTime2 = getConvertedStartEndTime(time2)


function getConvertedStartEndTime(time){
    time = time.split('-').map(function(item){ return item.replace('PM', '10000').replace('AM', 1)});
    time = time.map(function(item){ return item.split(':')});
    var time2StartConverted = time[0].reduce(function (a, b) {
    return parseInt(a) + parseInt(b);
    });
    var time2EndConverted = time[1].reduce(function (a, b) {
        return parseInt(a) + parseInt(b);
    });
    return [time2StartConverted, time2EndConverted]
}

知道你可以在日期之间进行比较

我要做的是创建一个函数,将这些字符串拆分成一个 multi-dimensional 数组:

var timeSegments = function(time) {
   var timeArray = time.split("-");
   for(i = 0; i < timeArray.length; i++) {
       timeArray[i] = timeArray[i].split(":");
   }
   return timeArray;
}

然后,我 运行 两个时间段的函数 :

time1 = timeSegments('10:00:AM-12:00:PM');
time2 = timeSegments('10:30:AM-11:00:AM');

time1 的输出应该是:

[
    [
        0: "10"
        1: "00"
        2: "AM"
    ], [
        0: "12"
        1: "00"
        2: "PM"
    ]
]

time2 的输出应该是:

[
    [
        0: "10"
        1: "30"
        2: "AM"
    ], [
        0: "11"
        1: "00"
        2: "AM"
    ]
]

您现在可以通过比较这些数组中的值来比较两个时间段。