Moment.js Date Ranges Plugin
The Date Ranges Plugin is a moment.js plugin that can be used when working with date ranges is necessary.
Write the below command in the terminal to install Ranges Plugin:
npm install moment-range
The following are some of the functions in this plugin:
- adjacent
- center
- contains
- within
- overlaps
- intersect
- isRange
- by
- byRange
- reverseBy
- reverseByRange
The below examples will help to understand some of the methods of the Date Ranges Plugin.
Example 1:
Javascript
import Moment from 'moment' ; import pkg from 'moment-range' ; const { extendMoment } = pkg; const moment = extendMoment(Moment); const start = new Date(2022, 0, 21); const end = new Date(2022, 6, 16); const r = moment.range(start, end); let date1 = moment( new Date(2022,4,1)); let date2 = moment( new Date(2022,11,31)); console.log(r.contains(date1)); console.log(r.contains(date2)); |
Output:
Example 2:
Javascript
import Moment from 'moment' ; import pkg from 'moment-range' ; const { extendMoment } = pkg; const moment = extendMoment(Moment); const start1 = new Date(2022, 0, 21); const start2 = new Date(2022, 6, 1); const end1 = new Date(2022, 6, 16); const end2 = new Date(2022, 11, 31); let range1 = moment.range(start1, end1); let range2 = moment.range(start2, end2); let range = range1.add(range2); console.log(range.start.format( "dddd, Do MMM YYYY, h:mm:ss A" )); console.log(range.end.format( "dddd, Do MMM YYYY, h:mm:ss A" )); |
Output:
Reference: https://momentjs.com/docs/#/plugins/range/