In this article, we are going to implement the logic to get the date range between the two dates using moment js and plain javascript. In other words, we are going to find the list of dates that come between the two dates.
If you have not created the project, then please create a folder and call it “daterange”. Open the folder and create a file called index.js. Now it’s time to import moment.js into the project. You can achieve this by 2 methods.
- By including the moment.js file inside the script tag. For this, you would need an HTML file, let’s call it index.html. If you are going by this method, then please create an HTML file inside the root folder, i.e., daterange. The base content of this file would be something like this –
<!DOCTYPE html> <html lang="en"> <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>DateRange</title> <!--Include the moment js file here--> <script type="text/JavaScript" src="https://MomentJS.com/downloads/moment.js"></script> </head> <body> </body> </html>
- By using Node.js, Make sure you have Node.js and npm installed on your system. You can use the following command to install MomentJs inside your root folder, ie. daterange in this case. The file path would be daterange/index.js.
npm install moment
Include MomentJs in your file like this –
let moment = require('moment'); //Include moment in your JS file
If you want to write the logic in a JS file then this method is recommended.
We are done with the basic setup. Now it’s time to write the code to get the date range between the two dates. Here is the code snippet –
let moment = require('moment'); //Include moment in your JS file let dateArr = []; //Array where dates will be stored let fromDate = new Date(moment().format('MM-DD-YYYY')); //From Date //Let's assume the endDate to be 15 days later from today let endDate = new Date(moment().add(15, 'days').format('MM-DD-YYYY')); //Logic for getting rest of the dates between two dates("FromDate" to "EndDate") while(fromDate < endDate){ dateArr.push(moment(fromDate).format('ddd DD-MM')); let newDate = fromDate.setDate(fromDate.getDate() + 1); fromDate = newDate(newDate); } //Print all dates console.log(dateArr)
node index.js
That’s it. This will return the list of the rest of the dates that lie between the two given dates. Hope you get the desired output. Happy coding 🙂
Do comment below if you are still facing any issues. Happy to help. Thanks.