[英]How to get three month ago date in javascript in the format as YYYYDDMM efficiently
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. 有没有办法在javascript中执行此操作。 I know that I can use Date d = new Date(); 我知道我可以使用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. 但现在我不想做解析并获得三个月前的约会。
var dt = new Date('13 June 2013');
dt.setMonth(dt.getMonth()-1)
Then you can use this piece of code from this answer to 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? 如果你在3月31日减去一个月,会发生什么? You can't get Feb 31! 你不能得到2月31日! See this answer for more details. 有关详细信息,请参阅此答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.