Javascript 如何使用 Momentjs 获取昨天的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31448557/
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 06:43:19  来源:igfitidea点击:

How to get yesterday's date with Momentjs?

javascriptdatemomentjs

提问by ToTa

So, my question is simple, how do I get yesterday's date with MomentJs ? In Javascript it is very simple, i.e.

所以,我的问题很简单,我如何获得昨天与 MomentJs 的约会?在Javascript中它非常简单,即

today = new Date();
yesterday = new Date(today.setDate(today.getDate() - 1))

console.log(yesterday)

But how do I achieve this with MomentJs ?

但是我如何使用 MomentJs 实现这一点?

回答by Aleks

Just like this: moment().subtract(1, 'days'). It will give you the previous day with the same exact current time that is on your local pc.

就像这样:moment().subtract(1, 'days')。它将为您提供前一天与您本地 PC 上相同的当前时间。

回答by Sai Ram

Also :

还 :

moment().subtract(1, 'day')

It will give you the previous day with the same exact current time that is on your local pc.

它将为您提供前一天与您本地 PC 上相同的当前时间。

回答by Fizer Khan

When we get yesterday's date, there are three possibilties

当我们得到昨天的日期时,有三种可能性

1.Get yesterday date with current timing

1.使用当前时间获取昨天的日期

moment().subtract(1, 'days').toString()

2.Get yesterday date with start of the day

2.从一天的开始获取昨天的日期

moment().subtract(1, 'days').startOf('day').toString()      

3.Get yesterday date with end of the day

3.获取昨天的日期和一天的结束

moment().subtract(1, 'days').endOf('day').toString()

回答by Jan Hommes

moment().add(-1, 'days');

You can find more information in the docs.

您可以在文档中找到更多信息。

回答by Shanavas VH

You can easily subtract days from moment using

您可以使用

var yesterday = moment().subtract(1, 'days')

var yesterday = moment().subtract(1, 'days')

And for finding the previous date

并查找上一个日期

var previousDay = moment('2017/11/6', 'YYYY/MM/DD').subtract(1, 'days')

var previousDay = moment('2017/11/6', 'YYYY/MM/DD').subtract(1, 'days')

回答by Jojo Joseph

Yesterday's date in Momentjs in DD-MM-YYYY format.

Momentjs 中昨天的日期,采用 DD-MM-YYYY 格式。

const yesterdaydate = moment().subtract(1, "days").format("DD-MM-YYYY");
console.log(yesterdaydate)

回答by Louise Fitzpatrick Hayes

This worked for me:

这对我有用:

var yesterday = new Date(dateInput.getTime());
yesterday.setDate(yesterday.getDate() - 1);
console.log(yesterday);

var tomorrow = new Date(dateInput.getTime());
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow);

dateB = moment(yesterday).format("YYYYMMDD");
dateA = moment(tomorrow).format("YYYYMMDD");
console.log(dateB);
console.log(dateA);