admin管理员组文章数量:1415119
I have this code where I want to get next 15 days from the start date
var fortnightStart = moment("15 04 2015", "DD MM YYYY");
for (var i = 1; i <= 15; i++) {
dates.push(fortnightStart.add(i, "days").format("D MMM"));
}
console.log(dates);
This is the output
["16 Apr", "18 Apr", "21 Apr", "25 Apr", "30 Apr", "6 May", "13 May", "21 May", "30 May", "9 Jun", "20 Jun", "2 Jul", "15 Jul", "29 Jul", "13 Aug"]
I don't know why its missing a few days.
I have this code where I want to get next 15 days from the start date
var fortnightStart = moment("15 04 2015", "DD MM YYYY");
for (var i = 1; i <= 15; i++) {
dates.push(fortnightStart.add(i, "days").format("D MMM"));
}
console.log(dates);
This is the output
["16 Apr", "18 Apr", "21 Apr", "25 Apr", "30 Apr", "6 May", "13 May", "21 May", "30 May", "9 Jun", "20 Jun", "2 Jul", "15 Jul", "29 Jul", "13 Aug"]
I don't know why its missing a few days.
Share Improve this question edited Apr 23, 2015 at 3:29 Yauheni Leichanok 1,7691 gold badge21 silver badges30 bronze badges asked Apr 23, 2015 at 2:24 user3214546user3214546 6,83115 gold badges55 silver badges98 bronze badges 1-
2
The
.add()
function modifies the moment (date) object. – Pointy Commented Apr 23, 2015 at 2:36
3 Answers
Reset to default 6On every iteration you add i
days to your initial date - so it keeps accumulating (+1, +2, +3 etc). You need to add not i
but simply 1
to fortnightStart
.
var fortnightStart = moment("15 04 2015", "DD MM YYYY");
for (var i = 1; i <= 15; i++) {
// 1, not i
dates.push(fortnightStart.add(1, "days").format("D MMM"));
}
console.log(dates);
The problem is that .add
modifies the object passed in instead of creating a new date. To keep your code in its original style, you need to clone the date before adding to it.
dates.push(fortnightStart.clone().add(i, "days").format("D MMM"));
Or:
dates.push(moment(fortnightStart).add(i, "days").format("D MMM"));
The reason you're missing dates is because 'date.add' changes the current variable. E.g.
date = moment("15 04 2015", "DD MM YYYY");
date.add(1, "days");
console.log(date); // This will give you "16 04 2015"
For your code to work correctly, you need to make sure that either:
1) The 'add' method doesn't change your original value by adding to a clone. e.g.
dates.push(fortnightStart.clone().add(i, "days").format("D MMM"));
OR
2) You only add 1 day every loop instead if 'i' days. e.g.
dates.push(fortnightStart.clone().add(1, "days").format("D MMM"));
本文标签: dateDays are not added properly with momentJS in JavaScriptStack Overflow
版权声明:本文标题:date - Days are not added properly with momentJS in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745221062a2648397.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论