Carl Edwards
Carl Edwards

Reputation: 14434

Creating an array of times in 24/12 hour format using moment.js

I just added moment.js to my project and want to create a couple of select boxes with the time of day on every hour and half hour. It would look something like this:

['12:00', '12:30', '1:00', '1:30', '2:00', '2:30'...'5:00', '5:30'];

I was wondering if there was a way moment.js was capable of generating an array in the same manner it can generate the days of the week:

moment.weekdays();

Essentially I want to populate my select input with these hourly options as labels and the values in 24 hour format. What would be my best bet here? Would I convert the 12 hour time within my loop or is there an even better option where moment can create an object with both values? Either way, I'm all ears.

Upvotes: 2

Views: 2444

Answers (3)

A. Moynet
A. Moynet

Reputation: 490

I found a solution more human readable with moment.

const startOfDay = moment().startOf('day');
const hours = Array(48).fill(null).map((_, i) => startOfDay.add(i ? 30 : 0, 'minutes').format('HH:mm'))

Upvotes: 0

Bang
Bang

Reputation: 1

you can always do something like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script >
  const generateHour = () => {
    const arrHours = []
    for (let h = 0; h < 48; h++) {
      arrHours.push(moment({
        hour: Math.floor(h / 2),
        minute: h % 2 === 0 ? 0 : 30
      }).format('HH:mm'))
    }
    console.log(arrHours)
 }
generateHour()
</script>

Upvotes: -1

Hassan Imam
Hassan Imam

Reputation: 22544

You can use array#from to create array of times

const hours = Array.from({
  length: 48
}, (_, hour) => moment({
    hour: Math.floor(hour / 2),
    minutes: (hour % 2 === 0 ? 0 : 30)
  }).format('HH:mm')
);
console.log(hours);
<script src="https://rawgit.com/moment/moment/2.24.0/min/moment.min.js"></script>

Upvotes: 4

Related Questions