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

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

    Allocating the resulting array to avoid the overhead of push, parameter validation and locale specifics notwithstanding:

        function generate_series(step) {
            const dt = new Date(1970, 0, 1);
            const rc = [];
            while (dt.getDate() === 1) {
                rc.push(dt.toLocaleTimeString('en-US'));
                dt.setMinutes(dt.getMinutes() + step);
            }
            return rc;
        }
    

    Here's a demo snippet.

    function generate_series(step) {
      const dt = new Date(1970, 0, 1);
      const rc = [];
      while (dt.getDate() === 1) {
        rc.push(dt.toLocaleTimeString('en-US'));
        dt.setMinutes(dt.getMinutes() + step);
      }
      return rc;
    }
    
    function on_generate_series(step) {
      const dt = new Date(1970, 0, 1);
      const el = document.getElementById("series")
      while (el.firstChild)
        el.removeChild(el.firstChild);
      const series = generate_series(step);
      while (series.length > 0) {
        let item = document.createElement("div");
        item.innerText = series.shift();
        el.appendChild(item);
      }
    }

    24 Hour Minute Series

提交回复
热议问题