Get String in YYYYMMDD format from JS date object?

后端 未结 30 1730
一个人的身影
一个人的身影 2020-11-22 10:47

I\'m trying to use JS to turn a date object into a string in YYYYMMDD format. Is there an easier way than concatenating Date.getYear()

相关标签:
30条回答
  • 2020-11-22 11:42

    You can use the toISOString function :

    var today = new Date();
    today.toISOString().substring(0, 10);
    

    It will give you a "yyyy-mm-dd" format.

    0 讨论(0)
  • 2020-11-22 11:42

    Use padStart:

    Date.prototype.yyyymmdd = function() {
        return [
            this.getFullYear(),
            (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
            this.getDate().toString().padStart(2, '0')
        ].join('-');
    };
    
    0 讨论(0)
  • 2020-11-22 11:44

    If you don't need a pure JS solution, you can use jQuery UI to do the job like this :

    $.datepicker.formatDate('yymmdd', new Date());
    

    I usually don't like to import too much libraries. But jQuery UI is so useful, you will probably use it somewhere else in your project.

    Visit http://api.jqueryui.com/datepicker/ for more examples

    0 讨论(0)
  • 2020-11-22 11:44

    var someDate = new Date();
    var dateFormated = someDate.toISOString().substr(0,10);
    
    console.log(dateFormated);

    0 讨论(0)
  • 2020-11-22 11:46

    I don't like modifying native objects, and I think multiplication is clearer than the string padding the accepted solution.

    function yyyymmdd(dateIn) {
      var yyyy = dateIn.getFullYear();
      var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
      var dd = dateIn.getDate();
      return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
    }
    
    var today = new Date();
    console.log(yyyymmdd(today));

    Fiddle: http://jsfiddle.net/gbdarren/Ew7Y4/

    0 讨论(0)
  • 2020-11-22 11:46

    Little bit simplified version for the most popular answer in this thread https://stackoverflow.com/a/3067896/5437379 :

    function toYYYYMMDD(d) {
        var yyyy = d.getFullYear().toString();
        var mm = (d.getMonth() + 101).toString().slice(-2);
        var dd = (d.getDate() + 100).toString().slice(-2);
        return yyyy + mm + dd;
    }
    
    0 讨论(0)
提交回复
热议问题