How to check if the current time is between two times using moment.js?

Member

by domenico , in category: Javascript , a year ago

How to check if the current time is between two times using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year ago

@domenico 

To check if the current time is between two specific times using Moment.js, you can use the moment-range plugin. Here's an example of how you can do this:

  1. Install the moment-range plugin via npm:
1
npm install moment-range


  1. Import the necessary modules:
1
2
const moment = require('moment');
const momentRange = require('moment-range');


  1. Extend the moment object with the moment-range functionality:
1
const momentRangeExtended = momentRange.extendMoment(moment);


  1. Define the start and end times:
1
2
const startTime = moment('09:00', 'HH:mm');
const endTime = moment('18:00', 'HH:mm');


  1. Check if the current time is between the defined range:
1
2
3
4
5
6
7
const currentTime = moment();

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


This will compare the current time with the start and end times to check if it falls within the specified range.