问题描述
我想遍历一系列的日历日期,每次迭代为+1天。我会使用Java中的JodaTime构建的东西-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?
推荐答案
您可以使用在node.js应用程序中。
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'));
}
嗯...这看起来很像您已经在自己的代码中写的代码自己的答案。 Moment.js是一个更受欢迎的库,具有大量功能,但是我想知道哪个库的性能更好?也许您可以测试并告诉我们。 :)
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. :)
但是这些都不比JodaTime做得好。为此,您需要一个在JavaScript中实现TZDB的库。我列出了。
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.
另外,请当心通常用于。这也会影响NodeJS。
Also, watch out for problems with JavaScript dates in general. This affects NodeJS as well.
这篇关于遍历NodeJS中的一系列日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!