How do I subtract one week from this date in jquery?

this is my code

var myDate = new Date(); todaysDate = ((myDate.getDate()) + '/' + (myDate.getMonth()) + '/' + (myDate.getFullYear())); $('#txtEndDate').val(todaysDate); 

I need txtEndDate = today's date is one week

+49
javascript jquery
Dec 13 '11 at 12:47
source share
4 answers

You can change the date using setDate . It automatically adjusts the transition to new months / years, etc.

 var oneWeekAgo = new Date(); oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); 

Then go to the date of the string anyway you prefer.

+123
Dec 13 '11 at 12:50
source share

I would do something like

 var myDate = new Date(); var newDate = new Date(myDate.getTime() - (60*60*24*7*1000)); 
+15
Dec 13 '11 at 12:53 on
source share
 var now = new Date(); now.setDate(now.getDate() - 7); // add -7 days to your date variable alert(now); 
+7
Dec 13 '11 at 12:52
source share

Check out Date.js. This is really neat!

http://www.datejs.com/

Here are some ways to do this using Date.js:

 // today - 7 days // toString() is just to print it to the console all pretty Date.parse("t - 7 d").toString("MM-dd-yyyy"); // outputs "12-06-2011" Date.today().addDays(-7).toString("MM-dd-yyyy"); // outputs "12-06-2011" Date.today().addWeeks(-1).toString("MM-dd-yyyy"); // outputs "12-06-2011" 

As an unrelated side, pay attention to Moment.js ... I think 2 libraries complement each other :)

http://momentjs.com/

+3
Dec 13 '11 at 12:49
source share



All Articles