Format JavaScript date as yyyy-mm-dd

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

    When ES2018 rolls around (works in chrome) you can simply regex it

    (new Date())
        .toISOString()
        .replace(
            /^(?\d+)-(?\d+)-(?\d+)T.*$/,
            '$-$-$'
        )
    

    2020-07-14

    Or if you'd like something pretty versatile with no libraries whatsoever

    (new Date())
        .toISOString()
        .match(
            /^(?\d\d(?\d\d))-(?0?(?\d+))-(?
    0?(?\d+))T(?0?(?\d+)):(?0?(?\d+)):(?(?0?(?\d+))\.\d+)(?[A-Z][\dA-Z.-:]*)$/ ) .groups

    Which results in extracting the following

    {
        H: "8"
        HH: "08"
        M: "45"
        MM: "45"
        S: "42"
        SS: "42"
        SSS: "42.855"
        d: "14"
        dd: "14"
        m: "7"
        mm: "07"
        timezone: "Z"
        yy: "20"
        yyyy: "2020"
    }
    

    Which you can use like so with replace(..., '$/$/\'$ @ $:$') as at the top instead of .match(...).groups to get

    14/7/'20 @ 8:45
    

提交回复
热议问题