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

后端 未结 15 1731
耶瑟儿~
耶瑟儿~ 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:23

    In any case you need to do O(N) operations to enumerate array elements. However, you could iterate through Date objects itself.

    function timeArr(interval) //required function with custom MINUTES interval
    {
      var result = [];
      var start = new Date(1,1,1,0,0);
      var end = new Date(1,1,2,0,0);
      for (var d = start; d < end; d.setMinutes(d.getMinutes() + 5)) {
          result.push(format(d));
      }
    
      return result;
    }
    
    function format(inputDate) // auxiliary function to format Date object
    {
        var hours = inputDate.getHours();
        var minutes = inputDate.getMinutes();
        var ampm = hours < 12? "AM" : (hours=hours%12,"PM");
        hours = hours == 0? 12 : hours < 10? ("0" + hours) : hours;
        minutes = minutes < 10 ? ("0" + minutes) : minutes;
        return hours + ":" + minutes + " " + ampm;
    }
    

    Demo

提交回复
热议问题