使用Moment.js格式化日期并减去日期 [英] Format date and Subtract days using Moment.js

查看:907
本文介绍了使用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.

这篇关于使用Moment.js格式化日期并减去日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆