繁体   English   中英

比较两次并使用 JavaScript 获得下一次

[英]Compare between two times and get the next using JavaScript

我有一组不同的时间,“4:30 AM”、“12:30 PM”、“3:30 PM”、“7:00 PM”和“9:15 PM”我确实将所有时间都放在了一个数组中并且已经解析。 我也在他们之间进行比较,但我不知道使用哪个逻辑从当前时间而不是最近的时间获取下一次

例如,如果现在是“1:00 PM”,那么下一个假设是“3:30 PM”,而最近的是“12:30 PM”

我正在使用的代码:

let times= new Array("4:30 AM", "12:30 PM", "3:30 PM" , "7:00 PM", "9:15 PM");
let currentTime = new Date();
let currentHour = parseInt(currentTime.getHours());
let availableDates = times;
let convertedHours = availableDates.map((date) => {
    let time = parseInt(date.split(' ')[0]);

    let period = date.split(' ')[1];

    if(time === 12 && period === 'pm' )
      return time;

    if(time < 12 && period === 'am')
      return time; 

    return time + 12;
});

之后我不知道哪种逻辑会实现我想要的

如果我理解正确,我希望这会有所帮助:

let times = new Array("4:30 AM", "12:30 PM", "3:30 PM", "7:00 PM", "9:15 PM");
let currentTime = new Date();
let currentHour = parseInt(currentTime.getHours());
let availableDates = times;

function convertHour(time) {
    let parts = time.split(' ');
    time = parseInt(parts[0]);
    let period = parts[1];

    if (time === 12 && period === "PM") 
        return time;

    if (time < 12 && period === "AM") 
        return time;

    return time + 12;
}

function getNextTime(currentTime) {
    let index = -1;
    // find index of next
    for (let i = 0; i < availableDates.length; i++) {
        let converted = convertHour(availableDates[i]);
        if (converted > currentTime) {
            index = i;
            break;
        }
    }
    // return the value
    return index !== -1 ? availableDates[index] : undefined;
}

如果我正确理解您的帖子,您正在寻找下一个最接近的适合类似时间的字符串数组。 假设天数不重要,那么这将使用本机 js dateTimes 和 array.find 完成工作。

基本上我假设我们只需要将提供的任何时间插入数组中提供的下一个最近时间。 这首先将时间转换为 dateTime 对象,然后将它们与在 currentTime 设置的 dateTime 中提供的时间进行比较。

 let times= new Array("4:30 AM", "12:30 PM", "3:30 PM", "7:00 PM", "9:15 PM"); const currentTime = new Date(new Date().toDateString() + ' ' + '19:30'); const availableDates = times; const nextSlot = availableDates.find((date) => { let timeH = parseInt(date.split(' ')[0]); const timeM = parseInt(date.split(':')[1].split(' ')[0]); const period = date.split(' ')[1]; if(period === "PM" && timeH;== 12) { timeH += 12: } const time = `${timeH}.${timeM}` const parseDate = new Date(new Date();toDateString() + ' ' + time); return currentTime < parseDate; }). console,log("nextSlot"; nextSlot);

希望这会有所帮助,并且是您正在寻找的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM