【问题标题】:Create an array with time intervals and add 2 hours创建一个具有时间间隔的数组并添加 2 小时
【发布时间】:2022-01-20 00:06:33
【问题描述】:

我需要在 javascript 中创建一个元素数组,这会使我设置的某个时间增加 2 小时。 我举个例子。时间是

14:00.

我需要创建一个数组,其中包含截至 16:00 的所有 30 分钟间隔。

14:00
14:30
15:00
15:30

【问题讨论】:

  • 很好,您对此有何尝试?你做了什么研究?
  • 阅读How to Askminimal reproducible example。我们修复了您真诚地尝试自己修复的代码——我们不是为您编写的。

标签: javascript date time


【解决方案1】:

我要做的是创建两个方法:addTimecreateDateArray

addTime 函数上,我们使用将时间戳转换为Date 对象,这样您就更容易管理而不是14:00 字符串。

const addTime = (_dateTimestamp, addHours, addMinutes, addSeconds) => { 
 const date = new Date();
 date.setTime( _dateTimestamp );
 
 const newDate = new Date();
 if(addHours) newDate.setHours( date.getHours() + addHours );
 if(addMinutes) newDate.setMinutes( date.getMinutes() + addMinutes );
 if(addSeconds) newDate.setSeconds( date.getSeconds() + addSeconds );
 
 return newDate;
}

const createDateArray = (date, minuteInterval, amount) => { 
  let array = [];
  for(let i = 1; i <= amount; i++) {
    const time = addTime( date, 0, minuteInterval * i, 0);
    array.push( time );
  }
  return array;
}

const dateToIncrement = new Date().getTime();
const minutesInterval = 30; // every 30 minutes
const amountTimes = 10; // will run through 10 times, so it'll calculate the minutes 10 times

const result = createDateArray( dateToIncrement, minutesInterval, amountTimes );

console.log(result);

如果您愿意,还可以通过设置方法的第二个和最后一个参数将addTime 函数用于其他属性,例如小时和秒。

我希望上面的代码有意义并且你可以使用它。

【讨论】:

    【解决方案2】:

    这是一个将时间规范生成为字符串的函数。它可以采用可选的第二个参数来指定结束时间(您的问题中为 16:00)。

    两个实用函数将时间字符串转换为(和从)分钟数。

    最后,使用Array.from创建结果数组:

    const toMinutes = str => str.split(":").reduce((h, m) => h * 60 + +m);
    
    const toString = min => (Math.floor(min / 60) + ":" + (min % 60))
                           .replace(/\b\d\b/, "0$&");
    
    function slots(startStr, endStr="16:00") {
        let start = toMinutes(startStr); 
        let end = toMinutes(endStr);
        return Array.from({length: Math.floor((end - start) / 30) + 1}, (_, i) =>
            toString(start + i * 30)
        );
    }
    
    console.log(slots("14:00"));

    【讨论】:

      【解决方案3】:

      你可以像这样创建一个基本函数:

         function getTimes(start) {
          start = parseInt(start) * 2 + (+start.slice(-2) > 0);
          end = start+60/12;
          return Array.from({length: end - start}, (_, i) =>
              (((i + start) >> 1) + ":" + ((i + start)%2*3) + "0").replace(/^\d:/, "0$&"));
      };
      

      并与 :

      一起使用
      getTimes("14:00");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多