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

前端 未结 10 802
一生所求
一生所求 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 17:58
    var today = new Date();
    
    function formatDate(date) {
     var dd = date.getDate();
            var mm = date.getMonth() + 1; //January is 0!
            var yyyy = date.getFullYear();
            if (dd < 10) {
              dd = '0' + dd;
            }
            if (mm < 10) {
              mm = '0' + mm;
            }
            //return dd + '/' + mm + '/' + yyyy;
                 return yyyy + '/' + mm + '/' +dd ;
    
    }
    
    console.log(formatDate(today));
    
    0 讨论(0)
  • 2020-12-17 18:01
    function formatdate(userDate){
      var omar= new Date(userDate);
      y  = omar.getFullYear().toString();
      m = omar.getMonth().toString();
      d = omar.getDate().toString();
      omar=y+m+d;
      return omar;
    }
    console.log(formatDate("12/31/2014"));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 18:10

    If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.

    date('n/j/Y', '2020-02-07') // 2/7/2020
    date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
    date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
    
    

    Disclaimer: I developed Date-Mirror.

    0 讨论(0)
提交回复
热议问题