javascript 如何有效地以YYYYDDMM格式在javascript中获取三个月前的日期

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

How to get three month ago date in javascript in the format as YYYYDDMM efficiently

javascriptjavascript-framework

提问by javaMan

I know a way to do in java:

我知道一种用java做的方法:

Calendar c5 = Calendar.getInstance();
c5.add(Calendar.MONTH, -6);
c5.getTime(); //It will give YYYYMMDD format three months ago.

Is there a way to do this in javascript. I know that I can use Date d = new Date(); parse it and do some code to get the format. But now I dont want to do parsing and getting three month ago date.

有没有办法在javascript中做到这一点。我知道我可以使用 Date d = new Date(); 解析它并执行一些代码来获取格式。但现在我不想解析和获取三个月前的日期。

回答by sachleen

var dt = new Date('13 June 2013');
dt.setMonth(dt.getMonth()-1)

Then you can use this piece of code from this answerto convert it to YYYYMMDD

然后您可以使用此答案中的这段代码将其转换为 YYYYMMDD

 Date.prototype.yyyymmdd = function() {
   var yyyy = this.getFullYear().toString();
   var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
   var dd  = this.getDate().toString();
   return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
  };

d = new Date();
d.yyyymmdd();

Something to be careful of. If you're at Mar 31 and subtract a month, what happens? You can't get Feb 31! See thisanswer for more details.

有什么要小心的。如果你在 3 月 31 日减去一个月,会发生什么?你不能得到 2 月 31 日!有关更多详细信息,请参阅答案。