Iterate through a range of dates in NodeJS
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.
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'));
}