javascript 如何在javascript中创建一个小时和分钟的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25828303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:05:56  来源:igfitidea点击:

How to create an array with hours and minutes in javascript?

javascriptdate

提问by Patrioticcow

i am trying to create a time array, something like:

我正在尝试创建一个时间数组,例如:

1:00
1:15
1:30
1:45
2:00
2:15
...

here is my code, what it does is that it starts the time from current time upwoards:

这是我的代码,它的作用是从当前时间开始计时:

var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();

for (var i = h; i <= 24; i++) {
   for (var j = m; j <= 59; j++) {
       if (j % 15 === 0) {
            j = j === 0 ? '00' : j;
            if (i >= 12) {
                timeArray.push((i - 12) + ':' + j + ' PM');
            } else {
                timeArray.push(i + ':' + j + ' AM');
            }
        }
    }
}

the problem is that is mis over 46, like var m = 50;, then the array goes empty because j % 15doesn't get 0 no more.

问题是m结束了46,比如var m = 50;,然后数组变空,因为j % 15不再得到 0。

an ideas how to fix this?

一个想法如何解决这个问题?

thanks

谢谢

回答by Mike 'Pomax' Kamermans

If what you want is an array ["1:00", "1:15", ...] then why not just build that? It has nothing to do with "hours" and "minutes", only with "getting some obviously sequential numbers" right:

如果你想要的是一个数组 ["1:00", "1:15", ...] 那么为什么不直接构建它呢?它与“小时”和“分钟”无关,只与“获得一些明显的连续数字”有关:

var arr = [], i, j;
for(i=0; i<24; i++) {
  for(j=0; j<4; j++) {
    arr.push(i + ":" + (j===0 ? "00" : 15*j) );
  }
}

done. Find your current time nearest a 15 minute block:

完毕。查找最接近 15 分钟时间段的当前时间:

var d = new Date(),
    h = d.getHours(),
    m = 15 * Math.floor(d.getMinutes()/15),
    stamp = h + ":" + (m === 0 ? "00" : m);

And just reorder the timeslots:

只需重新排序时间段:

var pos = arr.indexOf(stamp),
    timelist = arr.slice(pos).concat(arr.slice(0,pos));

回答by ?ukasz

I think you can do it simpler by using JavaScript Date API and by a simple trick.

我认为你可以通过使用 JavaScript Date API 和一个简单的技巧来更简单地做到这一点。

In loop all you need is to add 15 * 60 seconds (one quarter of an hour) to timestamp and print. Only calculate the closest full time (11:57 -> 12:00) at the beginning, then add as much quarters as you need.

在循环中,您只需将 15 * 60 秒(四分之一小时)添加到时间戳并打印。开始时只计算最接近的全职时间 (11:57 -> 12:00),然后根据需要添加尽可能多的季度。

Please see the code:

请看代码:

var date, array = [];
date = new Date();

// Here we will find the closest time
// If it's 13:09 we'll iterate to 13:15 and stop
//
// We'll iterate fifteen times in the worst case scenario
while (date.getMinutes() % 15 !== 0) {
    date.setMinutes ( date.getMinutes() + 1 );
}

// A whole day has 24 * 4 quarters of an hour
// Let's iterate using for loop
for (var i = 0; i < 24 * 4; i++) {
    array.push(date.getHours() + ':' + date.getMinutes());
    date.setMinutes ( date.getMinutes() + 15);
}

console.log(array);

// Now in Poland it's 18:10 so the result is an array of 96 elements 
// ["18:15", "18:30", "18:45", "19:0", ... "17:30", "17:45", "18:0"]
// As you may noticed, there is a need to format date when it's a full hour.
// We have 18:0 but we expect 18:00. This will be more understandable for users.
// We can open another discussion to find the best way to do that ;)

回答by Oriol

Try this:

试试这个:

var timeArray = [],
    d = new Date(),
    h = d.getHours(),
    m = d.getMinutes(),
    meridiem = ['AM','PM'];
for (var i = h; i < 24; ++i) {
    for (var j = i==h ? Math.ceil(m/15) : 0; j < 4; ++j) {
        timeArray.push(i%12 + ':' + (j*15||'00') + ' ' + meridiem[i/12|0]);
    }
}

回答by Mariano Desanze

The main problem is that the inner loop (j) starts at mvariable, and that probably is not zero at most times of the day. So for the first loop of ithat is ok. But for next loop you want that to be zero. You can fix that by assigning that mvariable to zero at the end of the ifor loop.

主要问题是内部循环 ( j) 从m变量开始,并且在一天中的大部分时间可能不为零。所以对于第一个循环是i可以的。但是对于下一个循环,您希望它为零。您可以通过mifor 循环结束时将该变量分配为零来解决该问题。

And try not to mix the variables that are for calculations (integers) with the ones you use for formatting the time (strings). You are doing that for jin here:

并且尽量不要将用于计算的变量(整数)与用于格式化时间的变量(字符串)混合在一起。你这样做是为了j

j = j === 0 ? '00' : j;

Here is the code I'd use (I also fixed the AM for 12 midnight and skiped most iteration of j by simply incrementing by 15 instead of by 1):

这是我要使用的代码(我还将 AM 固定为午夜 12 点,并通过简单地增加 15 而不是增加 1 跳过了 j 的大部分迭代):

var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = Math.ceil(d.getMinutes() / 15) * 15;

for (var i = h; i <= 24; i++) {
  for (var j = m; j <= 59; j += 15) {
    var mf = j === 0 ? '00' : j;
    var hf = i >= 12 ? (i - 12) : i;
    var amPm = i >= 12 && i < 24 ? 'PM' : 'AM';
    timeArray.push(hf + ':' + mf + ' ' +  amPm);
  }
  m = 0;
}

回答by Augusto Altman Quaranta

Try this

试试这个

var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();

for(var i=0; i< 24; i++){
    for(m = (m + 15 - m%15)%60; m < 60; m = m + 15){
        timeArray.push(h + ':' + m);
    }
    h = (h+1) % 24;
    timeArray.push(h + ':' + '00');
}

console.log(timeArray);

回答by Roman Krom

A one liner:

一个班轮:

const arr = Array(24 * 4).fill(0).map((_, i) => { return ('0' + ~~(i / 4) + ': 0' + 60  * (i / 4 % 1)).replace(/\d(\d\d)/g, '') });