1

Im trying to get the last week's date in the format: "2015-06-23" i.e "2015-06-16"

Js:

t = new Date();  // will give Tue Jun 23 2015 21:00:47 GMT-0700 (PDT)
t.toISOString(); // will give "2015-06-24T04:00:47.955Z"

the above date format i'm getting from the server. but I would like to get the last week date instead this week in the above format. How can i achieve that?

Thanks for the help in advance!

user1234
  • 3,000
  • 4
  • 50
  • 102

3 Answers3

4
  1. Create a Date.
  2. Go back 7 days.
  3. Convert to string, grabbing only the date portion.

Like so:

t = new Date();
t.setDate(t.getDate() - 7);
var date = t.toISOString().split('T')[0];
bearfriend
  • 10,322
  • 3
  • 22
  • 28
3

You can use moment.js

It's simple.

var t = moment.subtract(7, 'd').format('YYYY-MM-DD');

//For example: 2015-06-16

TryinHard
  • 4,078
  • 3
  • 28
  • 54
Gustavo Toro
  • 450
  • 4
  • 10
2

You can use setDate() to get the previous date

t = new Date();
t.setDate(t.getDate() - 7);//this will get you the previous date
t.toISOString();

Now for formatting, you can think of a library like momentjs or you can do it manually

var formatted = t.getFullYear() + '-' + (t.getMonth() < 9 ? '0' : '') + (t.getMonth() + 1) + (t.getDate() < 10 ? '0' : '') + '-' + (t.getDate());
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531