How can I remove 1 week from a date with JS without altering the date format (YYYY-MM-DD).
I saw several exemple but with the current date.
What I tried:
actual = '2017-04-10';
actual.setDate(actual.getDate() - 7);
Thanks.
How can I remove 1 week from a date with JS without altering the date format (YYYY-MM-DD).
I saw several exemple but with the current date.
What I tried:
actual = '2017-04-10';
actual.setDate(actual.getDate() - 7);
Thanks.
You need to convert your string to a Date
first.
Then, to get the format YYYY-MM-DD
you can use .toISOString()
and keep only the first 10 characters:
var d = new Date('2017-04-10'); // convert string to Date
d.setDate(d.getDate() - 7); // remove 7 days
var str = d.toISOString().slice(0, 10); // format YYYY-MM-DD
console.log(str);
The format is dictated by your operating system's regional settings and the format method you call on your date:
// You first need to turn your string into an actual JavaScript date:
actual = new Date('2017-04-10');
// Then you can use the Date API to modify it:
actual.setDate(actual.getDate() - 7);
// But the formatting of the date is determined by your operating system
// regional settings and the Date formatting method you call as well as
// how you, yourself decide to build your own custom format:
console.log(actual);
console.log(actual.toLocaleTimeString());
console.log(actual.toLocaleDateString());
console.log(actual.toISOString());
console.log(actual.getFullYear() + "-" + (actual.getMonth() + 1) + "-" + actual.getDate());
Your date needs to be a date object:
actual = new Date('2017-04-10');
actual.setDate(actual.getDate() - 7);