Format JavaScript date as yyyy-mm-dd

后端 未结 30 2705
再見小時候
再見小時候 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:06

    Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:

    yourDate.toISOString().split('T')[0]
    

    Where yourDate is your date object.

    Edit: @exbuddha wrote this to handle time zone in the comments:

    const offset = yourDate.getTimezoneOffset()
    yourDate = new Date(yourDate.getTime() - (offset*60*1000))
    return yourDate.toISOString().split('T')[0]
    

提交回复
热议问题