How do I get a date in YYYY-MM-DD format?

前端 未结 10 842
一生所求
一生所求 2020-12-17 17:16

Normally if I wanted to get the date I could just do something like

var d = new Date(); console.log(d);

The problem with doing that, is when I

10条回答
  •  感情败类
    2020-12-17 18:08

    Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.

    function returnYYYYMMDD(numFromToday = 0){
      let d = new Date();
      d.setDate(d.getDate() + numFromToday);
      const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
      const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
      return `${d.getFullYear()}-${month}-${day}`;
    }
    
    console.log(returnYYYYMMDD(-1)); // returns yesterday
    console.log(returnYYYYMMDD()); // returns today
    console.log(returnYYYYMMDD(1)); // returns tomorrow
    

    Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.

提交回复
热议问题