Get String in YYYYMMDD format from JS date object?

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

    Another way is to use toLocaleDateString with a locale that has a big-endian date format standard, such as Sweden, Lithuania, Hungary, South Korea, ...:

    date.toLocaleDateString('se')
    

    To remove the delimiters (-) is just a matter of replacing the non-digits:

    console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );

    This does not have the potential error you can get with UTC date formats: the UTC date may be one day off compared to the date in the local time zone.

提交回复
热议问题