Format JavaScript date as yyyy-mm-dd

后端 未结 30 2724
再見小時候
再見小時候 2020-11-22 01:28

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?

30条回答
  •  误落风尘
    2020-11-22 02:15

    const formatDate = d => [
        d.getFullYear(),
        (d.getMonth() + 1).toString().padStart(2, '0'),
        d.getDate().toString().padStart(2, '0')
    ].join('-');
    

    You can make use of padstart.

    padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.

    join('-') concatenates an array, adding '-' symbol between every elements.

    getMonth() starts at 0 hence the +1.

提交回复
热议问题