How to check if the time is in between given range using moment.js?

Member

by lily , in category: Javascript , 3 months ago

How to check if the time is in between given range using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 3 months ago

@lily 

To check if a specific time is in between a given range using Moment.js, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const moment = require('moment');

const startTime = moment('08:00:00', 'HH:mm:ss'); // Start time
const endTime = moment('18:00:00', 'HH:mm:ss'); // End time
const currentTime = moment(); // Current time

if (currentTime.isBetween(startTime, endTime)) {
  console.log('Current time is between the given range.');
} else {
  console.log('Current time is not between the given range.');
}


In this code, we first create Moment objects for the start time, end time, and current time. We then use the isBetween method provided by Moment.js to check if the current time is in between the start and end times. If the current time is in between the given range, it will print "Current time is between the given range." Otherwise, it will print "Current time is not between the given range."