Generate array of times (as strings) for every X minutes in JavaScript

后端 未结 15 1750
耶瑟儿~
耶瑟儿~ 2020-12-24 01:46

I\'m trying to create an array of times (strings, not Date objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the arr

15条回答
  •  庸人自扰
    2020-12-24 02:11

    You need only one loop, follow this approach

    var d = new Date(); //get a date object
    d.setHours(0,0,0,0); //reassign it to today's midnight
    

    Now keep adding 5 minutes till the d.getDate() value changes

    var date = d.getDate();
    var timeArr = [];
    while ( date == d.getDate() )
    {
       var hours = d.getHours();
       var minutes = d.getMinutes();
       hours = hours == 0 ? 12: hours; //if it is 0, then make it 12
       var ampm = "am";
       ampm = hours > 12 ? "pm": "am";
       hours = hours > 12 ? hours - 12: hours; //if more than 12, reduce 12 and set am/pm flag
       hours = ( "0" + hours ).slice(-2); //pad with 0
       minute = ( "0" + d.getMinutes() ).slice(-2); //pad with 0
       timeArr.push( hours + ":" + minute + " " + ampm );
       d.setMinutes( d.getMinutes() + 5); //increment by 5 minutes
    }
    

    Demo

提交回复
热议问题