75

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

Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
Infinity
  • 1,315
  • 4
  • 17
  • 25

4 Answers4

191

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.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • its setting the date as this ..Tue Dec 06 2011 18:24:34 GMT+0530 (India Standard Time) ..I need the date to be in this format ...13/11/2011 how do I do that now? plz help..thanks – Infinity Dec 13 '11 at 12:53
  • 2
    You may format it exactly as you like. The above code is for getting the date that is exactly one week from now. You can then go ahead and format it exactly as you're currently doing with `todaysDate` using `...getDate() + '/' ...`. Do note that `getMonth()` is 0-based, which is why you're getting `11` for December, there... – David Hedlund Dec 13 '11 at 12:55
  • @Asad I can confirm David's right here - it does work across month boundaries – James Cushing Jul 09 '15 at 09:42
  • Thanks for this :) – nescafe Jan 20 '18 at 08:48
24

I'd do something like

var myDate = new Date();
var newDate = new Date(myDate.getTime() - (60*60*24*7*1000));
  • 7
    so would I, but be aware of funny effects if the two dates are either side of daylight savings time. – Alnitak Dec 13 '11 at 12:59
  • Huge help! I like this method a bit more. I'm obsessed with one-liners though. So I use this: `var date = new Date(new Date().getTime() - (60*60*24*7*1000));` – Shaidar Jan 08 '17 at 16:19
  • You don't need the `.getTime()`. This works just as well: `new Date(new Date() - 60 * 60 * 24 * 7 * 1000)`. – Dan Dascalescu Feb 21 '18 at 08:33
  • @DanDascalescu wouldnt that invoke a whole new date generation? not that it would make much difference depending on the use case but id imagine less class construction the better – Cacoon Jan 08 '19 at 00:11
10
var now = new Date();
now.setDate(now.getDate() - 7); // add -7 days to your date variable 
alert(now); 
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
1

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/

Hristo
  • 45,559
  • 65
  • 163
  • 230