1

Suppose I get a date via a jquery calendar to a java script variable. e.g: var d = 02/12/2011

How can I manipulate that date variable using a js function or jq method where to get the date 3 month ahead of that date? I cant just do following know. Because every month does not have 30 days?

var futureDate=new Date(d);
futureDate.setDate(futureDate.getDate()+30*3);
Harshana
  • 7,297
  • 25
  • 99
  • 173
  • 2
    possible duplicate of [How to add months in javascript date?](http://stackoverflow.com/questions/5645058/how-to-add-months-in-javascript-date) – Rob Hruska Sep 26 '11 at 17:31

3 Answers3

3

Use futureDate.setMonth(futureDate.getMonth() + 3)

This will work towards the end of the year too. It roll over to the new year automatically.

Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • I'm interested in the reason for this downvote, since it's the same answer that got the checkmark here: http://stackoverflow.com/questions/5645058/how-to-add-months-in-javascript-date – Jonathan M Sep 26 '11 at 17:41
  • thanks Chetan..suppose its 1 year and 4 days something like that..then how its done pls – Harshana Sep 26 '11 at 18:00
  • Refer to https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date – Chetan S Sep 26 '11 at 18:44
  • Chetan: above does not work for edge cases. See below, http://www.markhneedham.com/blog/2009/01/07/javascript-add-a-month-to-a-date/ I have go ahead with Datejs which is pretty cool – Harshana Sep 27 '11 at 11:47
3

You can try using either the Date.js or Sugar.js libraries. They both have great date manipulation functions.

Here's an example using Sugar...

var futureDate = Date.create(d);
futureDate.addMonths(3);

The value d can be anything that Sugar understands as a date which is quite flexible.

Brian
  • 37,399
  • 24
  • 94
  • 109
  • Agreed. In fact @Chetan has a good answer for this simple problem. I just thought I would give a plug for some great date/time libraries that can help improve date manipulation, especially if you accept user entered dates (they both have great date parsing). – Brian Sep 26 '11 at 23:12
0

Here's a good routine that can handle that and lots of other date manipulations:

http://slingfive.com/pages/code/jsDate/jsDate.html

Jonathan M
  • 17,145
  • 9
  • 58
  • 91