javascript 获取上个月的日期javascript

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

Get previous month date javascript

javascriptjqueryasp.net

提问by Vicky

How can I get previous month date in javascript. Suppose you have today's date like:

如何在 javascript 中获取上个月的日期。假设您有今天的日期,例如:

var abc = new date(); 

It will return today's date for example 03-11-2015. Now I want to get 03-10-2015. This is 30 days less than todays date. How can I do this?

例如,它将返回今天的日期03-11-2015。现在我想得到03-10-2015. 这比今天的日期少了 30 天。我怎样才能做到这一点?

回答by Robert Shenton

var d = new Date();
d.setMonth(d.getMonth() - 1);

Check out momentjs, great little library for manipulating and formatting dates.

查看momentjs,用于操作和格式化日期的很棒的小库。

回答by Bustikiller

Complementing Robert Shenton's answer:

补充罗伯特·珊顿的回答:

var d = new Date();
var newMonth = d.getMonth() - 1;
if(newMonth < 0){
    newMonth += 12;
    d.setYear(d.getYear() - 1);
}
d.setMonth(newMonth);