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!
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!
Share Improve this question asked Jun 24, 2015 at 4:03 user1234user1234 3,1596 gold badges57 silver badges117 bronze badges 4- 1 momentjs. moment library is this something useful to you? – Shih-Min Lee Commented Jun 24, 2015 at 4:06
- 1 stackoverflow./a/3818198/507793 – Matthew Commented Jun 24, 2015 at 4:07
- This is javascript date + 7 days i hope you need it stackoverflow./questions/5741632/javascript-date-7-days – Cherryishappy Commented Jun 24, 2015 at 4:20
- I second moment.js. It saves a lot of brain cells. – Cymen Commented Jun 24, 2015 at 4:34
3 Answers
Reset to default 4- Create a
Date
. - Go back 7 days.
- 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];
You can use moment.js
It's simple.
var t = moment.subtract(7, 'd').format('YYYY-MM-DD');
//For example: 2015-06-16
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());