如何将此日期 'Wed Mar 9 09:48:09 PST 2016' 转换为 'YYYY-MM-DD HH:mm:ss' 格式?

How to convert this date 'Wed Mar 9 09:48:09 PST 2016' to 'YYYY-MM-DD HH:mm:ss' format?

我正在尝试将日期时间值从这种格式 Wed Mar 9 09:48:09 PST 2016 转换为以下格式 YYYY-MM-DD HH:mm:ss

我尝试使用 moment 但它给了我一个警告。

"Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Arguments: [object Object]
fa/<@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:9493
ia@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:10363
Ca@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15185
Ba@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15024
Aa@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:14677
Da@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15569
Ea@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15610
a@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:41
@http://localhost:1820/Home/Test:89:29
jQuery.event.dispatch@http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:5225:16
jQuery.event.add/elemData.handle@http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:4878:6
"

根据 https://github.com/moment/moment/issues/1407,我不应该尝试使用 moment() 来执行此操作,因为它不可靠。

如何可靠地将 Wed Mar 9 09:48:09 PST 2016 转换为以下格式 YYYY-MM-DD HH:mm:ss

您可以尝试使用 Date.toJSON() , String.prototype.replace() , trim()

var date = new Date("Wed Mar 9 09:48:09 PST 2016").toJSON()
           .replace(/(T)|(\..+$)/g,  function(match, p1, p2) {
             return match === p1 ? " " : ""
           });

console.log(date);

既然你用 标记了你的问题,我会用 moment 来回答。

首先,弃用是因为您在不提供格式规范的情况下解析日期字符串,并且该字符串不是 moment 可以直接识别的标准 ISO 8601 格式之一。使用格式说明符,它将正常工作。

var m = moment("Wed Mar 9 09:48:09 PST 2016","ddd MMM D HH:mm:ss zz YYYY");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // "2016-03-09 09:48:09"

其次,认识到在上面的代码中,zz只是一个占位符。 Moment 实际上并不解释时区缩写,因为只有 too many ambiguities("CST" 有 5 种不同的含义)。如果您需要将其解释为 -08:00,那么您必须自己进行一些字符串替换。

幸运的是,看起来(至少根据您的要求)您根本不需要任何时区转换,因此上面的代码将完成这项工作。