使用Moment.js格式化日期并减去日期
我想使用Moment.js以DD-MM-YYYY格式存储昨天日期的变量。所以如果今天是15-04-2015,我想减去一天,并有14-4-2015。
I would like a variable to hold yesterdays date in the following format DD-MM-YYYY using Moment.js. So if today is 15-04-2015 I would like to subtract a day and have 14-4-2015.
我尝试了一些组合,如:
Ive tried a few combinations like:
startdate = moment().format('DD-MM-YYYY');
startdate.subtract(1, 'd');
而
startdate = moment().format('DD-MM-YYYY').subtract(1, 'd');
,而且
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY')
但没有得到它。
您有多个异常发生。第一个在您的帖子中已被编辑,但它与调用方法的顺序有关。
You have multiple oddities happening. The first has been edited in your post, but it had to do with the order that the methods were being called.
.format
返回一个字符串。字符串没有减法
方法。
.format
returns a string. String does not have a subtract
method.
第二个问题是你减去一天,但实际上将其保存为变量。
The second issue is that you are subtracting the day, but not actually saving that as a variable.
然后,您的代码应如下所示:
Your code, then, should look like:
var startdate = moment();
startdate = startdate.subtract(1, "days");
startdate = startdate.format("DD-MM-YYYY");
但是,您可以链接在一起;这将是:
However, you can chain this together; this would look like:
var startdate = moment().subtract(1, "days").format("DD-MM-YYYY");
区别在于我们正在将startdate设置为在startdate上进行的更改,因为时刻是破坏性的。
The difference is that we're setting startdate to the changes that you're doing on startdate, because moment is destructive.