Javascript 使用 Moment.JS 添加天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29369599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:16:34  来源:igfitidea点击:

Adding Days using Moment.JS

javascriptdatetitanium-mobileappceleratormomentjs

提问by Simon Hume

Having a few issues with simply adding a day to a few dates in an Appcelerator project using moment.js

在使用 moment.js 的 Appcelerator 项目中简单地将一天添加到几个日期时遇到一些问题

All I want to do, is grab today's date and then display it in the DD format (01) and then get the next 6 days as well.

我想要做的就是获取今天的日期,然后以 DD 格式 (01) 显示它,然后获取接下来的 6 天。

Here is what I'm trying:

这是我正在尝试的:

var todayDate = moment();

var day1 = todayDate.format("DD");
var day2 = todayDate.add(1, 'days').format("DD");
var day3 = todayDate.add(2, 'days').format("DD");
var day4 = todayDate.add(3, 'days').format("DD");
var day5 = todayDate.add(4, 'days').format("DD");
var day6 = todayDate.add(5, 'days').format("DD");
var day7 = todayDate.add(6, 'days').format("DD");

But, the output I get is the following:

但是,我得到的输出如下:

[INFO] :   31
[INFO] :   01
[INFO] :   03
[INFO] :   06
[INFO] :   10
[INFO] :   15
[INFO] :   21

It should read:

它应该是:

[INFO] :   31
[INFO] :   01
[INFO] :   02
[INFO] :   03
[INFO] :   04
[INFO] :   05
[INFO] :   06

What am I doing wrong?

我究竟做错了什么?

Simon

西蒙

回答by Cyril N.

You add days to the same variable :

您将天数添加到同一变量:

say todayDateis 31. First line, you add 1 day to todayDate, so it becomes 01. Then you add 2 days to todayDate(that is now "01") so it becomes 03 etc ...

todayDate是 31。第一行,你加 1 天todayDate,所以它变成 01。然后你加 2 天todayDate(现在是“01”),所以它变成 03 等等......

Do this instead (depending on what you need of course) :

改为执行此操作(当然取决于您的需要):

var day1 = moment().format("DD");
var day2 = moment().add(1, 'days').format("DD");
var day3 = moment().add(2, 'days').format("DD");
var day4 = moment().add(3, 'days').format("DD");
var day5 = moment().add(4, 'days').format("DD");
var day6 = moment().add(5, 'days').format("DD");
var day7 = moment().add(6, 'days').format("DD");

or just add 1every time ;)

或者1每次都添加;)

var todayDate = moment();

var day1 = todayDate.format("DD");
var day2 = todayDate.add(1, 'days').format("DD");
var day3 = todayDate.add(1, 'days').format("DD");
var day4 = todayDate.add(1, 'days').format("DD");
var day5 = todayDate.add(1, 'days').format("DD");
var day6 = todayDate.add(1, 'days').format("DD");
var day7 = todayDate.add(1, 'days').format("DD");

回答by Artur Stary

You refer to the same variable

你指的是同一个变量

You add N days to todayDate, so next add-method will add N days to the already increased value of todays date, which is no longer 'today'

您将 N 天添加到todayDate,因此 next add-method 会将 N 天添加到今天日期已经增加的值中,该值不再是“今天”