简体   繁体   中英

How to create an array with current time and next 10 five minute interval times using javascript?

I need to create one array in javascript like this. It should contain current time + next 10 times with the interval of 5 mins

array = [1.45, 1.50, 1.55, 2.00, 2.05, 2.10, 2.15, 2.20, 2.25, 2.30];

How I will create this kind of an array using javascript.

var date = new Date(), interval=5, arr=[];
for(var i=0;i<10;i++){
  date.setMinutes(date.getMinutes() + interval);
  arr.push(date.getHours() + '.' + date.getMinutes());
}
/*
arr is the array you want.
e.g. ["21.17", "21.22", "21.27", "21.32", "21.37", "21.42", 
        "21.47", "21.52", "21.57", "22.2"]
*/

You should use Javascript's Date object. It's a little bit weird to use decimals to represent time. After all, does 1.50 stand for one hour and a half, or for one hour and fifty minutes?

Having said that, here is the code:

array = [];
var d = new Date();
for (var i = 0; i < 10; i++){
  array.push( d );
  d = new Date( d.getTime() + 5*60*1000 );  // 5 minutes in milliseconds
}

Therefore, the array now contains 10 Date objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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