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

JavascriptJquery

Javascript Problem Overview


this is my code

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

I need txtEndDate's value = today's date - one week

Javascript Solutions


Solution 1 - Javascript

You can modify a date using setDate. It automatically corrects for shifting to new months/years etc.

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

And then go ahead to render the date to a string in any matter you prefer.

Solution 2 - Javascript

I'd do something like

var myDate = new Date();
var newDate = new Date(myDate.getTime() - (60*60*24*7*1000));

Solution 3 - Javascript

var now = new Date();
now.setDate(now.getDate() - 7); // add -7 days to your date variable 
alert(now); 

Solution 4 - Javascript

Check out Date.js. Its really neat!

http://www.datejs.com/

Here are a couple of ways to do it 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 note, do check out Moment.js as well... I think the 2 libraries compliment each other :)

http://momentjs.com/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInfinityView Question on Stackoverflow
Solution 1 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 2 - JavascriptJean-Philippe GireView Answer on Stackoverflow
Solution 3 - JavascriptSandeep G BView Answer on Stackoverflow
Solution 4 - JavascriptHristoView Answer on Stackoverflow