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?
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 .
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.
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.
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')); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With