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

后端 未结 15 1726
耶瑟儿~
耶瑟儿~ 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条回答
  •  -上瘾入骨i
    2020-12-24 02:07

    My solution with emphasize on readability. It first creates objects that represent correct times and then formats them to strings. JsFiddle https://jsfiddle.net/6qk60hxs/

    var periods = ['AM', 'PM'];
    var hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    var minutes = ["00", "05", 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
    
    
    timeObj = add([{}], "p", periods);
    timeObj = add(timeObj, "h", hours);
    timeObj = add(timeObj, "m", minutes);
    
    times = []
    for (t of timeObj) {
      times.push(t.h + ':' + t.m + ' ' + t.p);
    }
    
    console.log(times)
    
    function add(tab, prop, val) {
      var result = [];
      for (t of tab) {
        for (v of val) {
          tc = _.clone(t);
          tc[prop] = v;
          result.push(tc);
        }
      }
      return result
    }
    

提交回复
热议问题