Moment js interval for a day in 12 hours format

2019-08-12 13:19发布

问题:

In 12 hours format,i have to create a interval of 15 minutes in moment which is working fine with 30 minutes interval.

var hours = [];
    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')
      );
    }
  console.log( hours);

But when work with 15 minutes shows the wrong format.can anone help?

var hours = [];
    for (let hour = 0; hour < 24; hour++) {
      hours.push(moment({ hour }).format('h:mm a'));
      hours.push(
        moment({
          hour,
          minute: 15
        }).format('h:mm a')
      );
    }
  console.log( hours);

Demo: http://jsfiddle.net/remus/rLjQx/

Expected Op: 12:00, 12:15,12:30,12:45,1:00 etc

回答1:

You are only pushing in two values per loop. You need to push in four values for every hour. One way would be to loop minutes within the hour loop hours:

var hours = [];
for (let hour = 0; hour < 24; hour++) {
  for (let minute = 0; minute < 60; minute += 15) {
    hours.push(moment({hour, minute }).format('h:mm a'));
  }
}

console.log(hours);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>