Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a range of dates in NodeJS

I would like to iterate through a range of calender dates, each iteration is +1 day. I would use something built around JodaTime in Java - is there something similar in NodeJS?

like image 523
nwaltham Avatar asked Jun 18 '13 08:06

nwaltham


People also ask

How to loop through a dates range in JavaScript?

To loop through a date range with JavaScript, we can use a while loop. We create the start and end date objects that are the start and end dates of the date range. loop is the variable with the start date. We increment loop in the while loop until it's bigger than or equal to end .

How to run a loop for date in JavaScript?

One way to loop through a date range with JavaScript is to use a while loop. We can create variables for the start and end dates. Then we can increment the start date until it reaches the end date. We have the start and end variables with the start and end date respectively.

How to increment date in for loop in JavaScript?

The following are the JavaScript code examples to increment a date by 1 day using the setDate() and getDate() methods. The JavaScript method setDate() sets the day of the date object.


2 Answers

You can use moment.js in a node.js application.

npm install moment 

Then you can very easily do this:

var moment = require('moment');  var a = moment('2013-01-01'); var b = moment('2013-06-01');  // If you want an exclusive end date (half-open interval) for (var m = moment(a); m.isBefore(b); m.add(1, 'days')) {   console.log(m.format('YYYY-MM-DD')); }  // If you want an inclusive end date (fully-closed interval) for (var m = moment(a); m.diff(b, 'days') <= 0; m.add(1, 'days')) {   console.log(m.format('YYYY-MM-DD')); } 

Hmmm... this looks a lot like the code you already wrote in your own answer. Moment.js is a more popular library has tons of features, but I wonder which one performs better? Perhaps you can test and let us know. :)

But neither of these do as much as JodaTime. For that, you need a library that implements the TZDB in JavaScript. I list some of those here.

Also, watch out for problems with JavaScript dates in general. This affects NodeJS as well.

like image 52
Matt Johnson-Pint Avatar answered Sep 23 '22 03:09

Matt Johnson-Pint


I would propose a change to the earlier response by Matt. His code will cause a mutation on the a object. try this...

var moment = require('moment'); var a = moment('2013-01-01'); var b = moment('2013-06-01');  for (var m = moment(a); m.isBefore(b); m.add(1, 'days')) {     console.log(m.format('YYYY-MM-DD')); } 
like image 45
ice.nicer Avatar answered Sep 19 '22 03:09

ice.nicer