3

I want array of past five minutes in hour:minute format like below , But is there any other smarter way to do it easily ?

     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];
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Gracie williams
  • 1,287
  • 2
  • 16
  • 39

1 Answers1

3

I'd start by creating a reusable subtractMinutes function.

You could then create a new array of 5 items and use that subtractMinutes on each. The first item would have 0 minutes subtracted, the second would have 1 minute subtracted, so-on and so-forth.

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) );

Related documentation, references:

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56