最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

I know a way to do in 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.

I know a way to do in 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.

Share Improve this question asked Jun 13, 2012 at 19:16 javaManjavaMan 6,68020 gold badges68 silver badges95 bronze badges 2
  • 1 Sure you can use a library like date.js which is probably around 25kb of stuff you will not use to do something 5 lines of JavaScript can do. – epascarello Commented Jun 13, 2012 at 19:19
  • 1 @epascarello I really want to see your 5 line javascript code with all edge cases covered ;) – javaMan Commented Jun 13, 2012 at 20:15
Add a comment  | 

1 Answer 1

Reset to default 18
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

 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 this answer for more details.

发布评论

评论列表(0)

  1. 暂无评论