Format JavaScript date as yyyy-mm-dd

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

    2020 ANSWER

    You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).

    Examples

    new Date().toLocaleDateString() // 8/19/2020
    
    new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
    
    new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
    
    new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
    
    new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
    
    new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)
    

    Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format. You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

    Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.

提交回复
热议问题