DEV Community

Dezina
Dezina

Posted on

Generating time slots using moment.js with start time & end time range

//Data
let x = {
slotInterval: 30,
openTime: '21:00',
closeTime: '05:00'
};

//Format the time
let startTime = moment(x.openTime, "HH:mm");

//Format the end time and the next day to it
let endTime = moment(x.closeTime, "HH:mm").add(1, 'days');

//Times
let allTimes = [];

//Loop over the times - only pushes time with 30 minutes interval
while (startTime < endTime) {
//Push times
allTimes.push(startTime.format("HH:mm"));
//Add interval of 30 minutes
startTime.add(x.slotInterval, 'minutes');
}

console.log(allTimes);

Top comments (1)

Collapse
 
rangercoder99 profile image
RangerCoder99

Moment.js library is deprecated (rip), and no longer in active development! Use something else like date-fns, Day.js

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay