This question already has answers here:
Format JavaScript date as yyyy-mm-dd
                                
                                    (32个答案)
                                
                        
                                去年关闭。
            
                    
我正在尝试重新格式化字符串日期,如下所述:

'25th May 1912' → 1912-05-2


我尝试使用Date.parse(),但会引发错误。

有什么建议么?

谢谢

最佳答案

您应该从日期中删除th,因此Date.parse返回NaN
这应该工作:

var input = '25th May 1912';
var validInput = input.replace(/(th|st|nd|rd)/, '');
var dateObj = new Date(Date.parse(validInput))
console.log(dateObj.getFullYear() + '-' + ('0' + (dateObj.getMonth()+1)).slice(-2) + '-' + ('0' + dateObj.getDate()).slice(-2));

09-26 12:46