-2

I need to get the date of constantly changing two weeks back so from today two weeks back in YYYY-MM-DD format. I got it with this code snippet that works, but is there a better way?

Thanks!!!

const twoWeeksBack = new Date(Date.now() - 12096e5).toISOString().slice(0, 10);

console.log(twoWeeksBack);
Jack Bou3r
  • 11
  • 2
  • 1
    This is duplicated here: https://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript?rq=1 and here: https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?rq=1 – luiscla27 Sep 26 '18 at 00:08

2 Answers2

-1

If you can use libraries, Moment.js is very useful for date manipulation

moment().subtract(2, 'weeks').format("YYYY-MM-DD")
Hofma Dresu
  • 432
  • 3
  • 13
-1

I'd recommend MomentJS for anything to do with time/date conversion.

Simply .subtract(2, 'weeks') and then .format('YYYY-MM-DD'):

const twoWeeksBack = moment(new Date()).subtract(2, 'weeks').format('YYYY-MM-DD');
console.log(twoWeeksBack);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71