Get String in YYYYMMDD format from JS date object?

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

提交回复
热议问题