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

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

    Manipulating with a date as with integer and using single loop:

    var interval = 5 * 60 * 1000; //5 minutes 
    var period = 24 * 60 * 60 * 1000; //dat period
    
    //just converts any time to desired string
    var toString = function toString(time){  
      var h = time.getHours();
      var m = time.getMinutes();
      var p = h >= 12 ? "PM" : "AM";
      h = h || 12;
      h = h > 12 ? h - 12 : h;  
      return ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2) + " " + p;
    }
    
    //start time
    var time = new Date(2010, 0, 1);
    
    //resulting array
    var times = [];
    
    for ( var t = +time; t < +time + period; t += interval){  
      var d = toString(new Date(t));  
      times.push(d);
    }
    
    0 讨论(0)
  • 2020-12-24 02:06

    Loops are unnecessary in this case.

    ES6

    //Array.from, only supported by Chrome 45+, Firefox 32+, Edge and Safari 9.0+
    //create an array of the expected interval
    let arr = Array.from({
      length: 24 * 60 / 5
    }, (v, i) => {
      let h = Math.floor(i * 5 / 60);
      let m = i * 5 - h * 60;
      //convert to 12 hours time
      //pad zero to minute
      if (m < 10) {
        m = '0' + m;
      }
      let label = 'AM';
      if (h > 12) {
        label = 'PM';
        h -= 12;
      }
      if (h === 0) {
        h = 12;
      }
      return h + ':' + m + ' ' + label;
    });
    
    document.body.textContent = JSON.stringify(arr);

    Wider browser support

    var arr = Array.apply(null, {
      length: 24 * 60 / 5
    }).map(function(v, i) {
      var h = Math.floor(i * 5 / 60);
      var m = i * 5 - h * 60;
      if (m < 10) {
        m = '0' + m;
      }
      var label = 'AM';
      if (h > 12) {
        label = 'PM';
        h -= 12;
      }
      if (h === 0) {
        h = 12;
      }
      return h + ':' + m + ' ' + label;
    });
    
    document.body.textContent = JSON.stringify(arr);

    0 讨论(0)
  • 2020-12-24 02:06
    const getTimes = (increment = 2) => {
      const times = [];
      for (let i = 0; i < 24; i++) {
        times.push({
          value: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:00 ${i < 12 ? 'AM' : 'PM'}`,
          label: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:00 ${i < 12 ? 'AM' : 'PM'}`,
        });
        for (let j = 60 / increment; j < 60; j += 60 / increment) {
          times.push({
            value: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:${Math.ceil(j)} ${i < 12 ? 'AM' : 'PM'}`,
            label: `${i === 0 || i - 12 === 0 ? 12 : i < 12 ? i : i - 12}:${Math.ceil(j)} ${i < 12 ? 'AM' : 'PM'}`,
          });
        }
      }
      return times;
    };
    
    
    0 讨论(0)
  • 2020-12-24 02:07

    if you have access to moment, you can always do something like this:

    const locale = 'en'; // or whatever you want...
    const hours = [];
    
    moment.locale(locale);  // optional - can remove if you are only dealing with one locale
    
    for(let hour = 0; hour < 24; hour++) {
        hours.push(moment({ hour }).format('h:mm A'));
        hours.push(
            moment({
                hour,
                minute: 30
            }).format('h:mm A')
        );
    }
    

    the result is the following array:

    ["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", "2:00 AM", "2:30 AM", "3:00 AM", "3:30 AM", "4:00 AM", "4:30 AM", "5:00 AM", "5:30 AM", "6:00 AM", "6:30 AM", "7:00 AM", "7:30 AM", "8:00 AM", "8:30 AM", "9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM", "5:00 PM", "5:30 PM", "6:00 PM", "6:30 PM", "7:00 PM", "7:30 PM", "8:00 PM", "8:30 PM", "9:00 PM", "9:30 PM", "10:00 PM", "10:30 PM", "11:00 PM", "11:30 PM"]
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-24 02:09

    If the interval is only to be set in minutes[0-60], then evaluate the below solution w/o creating the date object and in single loop:

    var x = 5; //minutes interval
    var times = []; // time array
    var tt = 0; // start time
    var ap = ['AM', 'PM']; // AM-PM
    
    //loop to increment the time and push results in array
    for (var i=0;tt<24*60; i++) {
      var hh = Math.floor(tt/60); // getting hours of day in 0-24 format
      var mm = (tt%60); // getting minutes of the hour in 0-55 format
      times[i] = ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + ap[Math.floor(hh/12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
      tt = tt + x;
    }
    
    console.log(times);

    0 讨论(0)
提交回复
热议问题