Get String in YYYYMMDD format from JS date object?

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

    Answering another for Simplicity & readability.
    Also, editing existing predefined class members with new methods is not encouraged:

    function getDateInYYYYMMDD() {
        let currentDate = new Date();
    
        // year
        let yyyy = '' + currentDate.getFullYear();
    
        // month
        let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
        mm = mm.substr(mm.length - 2);                  // take last 2 chars
    
        // day
        let dd = ('0' + currentDate.getDate());         // prepend 0
        dd = dd.substr(dd.length - 2);                  // take last 2 chars
    
        return yyyy + "" + mm + "" + dd;
    }
    
    var currentDateYYYYMMDD = getDateInYYYYMMDD();
    console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
    

提交回复
热议问题