Get String in YYYYMMDD format from JS date object?

后端 未结 30 2259
一个人的身影
一个人的身影 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

    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('-');
    };
    

提交回复
热议问题