javascript,以更轻松的方式度过5分钟

时间:2019-05-08 03:38:39

标签: javascript

我想要像下面这样的hour:minute格式的过去五分钟的数组,但是还有其他更聪明的方法可以轻松地做到这一点吗?

     var today = new Date();
     today.setSeconds(0);
     var last1 = new Date(today.getTime() - (1000*60));

     hour = last1.getHours();
     min = last1.getMinutes();
     final1 = hour+":"+min;

     var last2 = new Date(today.getTime() - (1000*120));
     var last3 = new Date(today.getTime() - (1000*180));
     var last4 = new Date(today.getTime() - (1000*240));
     var last5 = new Date(today.getTime() - (1000*300));

     var arr = [final1,final2,..and so on];

2 个答案:

答案 0 :(得分:3)

我将从创建一个可重用的subtractMinutes函数开始。

然后您可以创建一个由5个项目组成的新数组,并在每个项目上使用该subtractMinutes。第一项将连续减去0分钟,第二项将减去1分钟。

const subtractMinutes = (date,minutes) => new Date(date - minutes * 60000);

const getPastMinutes = (minutes, startDate = new Date()) => {
  return [...Array(minutes)].map((i,idx) => {
    let newDate = subtractMinutes(startDate,idx);
    let hour = newDate.getHours().toString().padStart(2,'0');
    let minute = newDate.getMinutes().toString().padStart(2,'0');
    return `${hour}:${minute}`;
  });
};

console.log( getPastMinutes(5) );

相关文档,参考文献:

答案 1 :(得分:-3)

您可以使用创建一个

Date.prototype.changeSeconds = function(seconds) {
    var t= new Date(this.valueOf());
    t.setMinutes(t.getMinutes() + seconds);
    return t;
}

function convertHourMin(lastDate) {
    hour = lastDate.getHours();
    min = lastDate.getMinutes();
    return hour+":"+min
}
var currentDate = new Date(),
    arr = [];
for (var i = 1; i <= 5; i ++) {
    arr.push(convertHourMin(currentDate.changeSeconds(-i)));
}
consolelog(arr)

这是一个演示链接:https://jsfiddle.net/9bqu1yjg/