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

时间:2016-03-09 18:18:06

标签: javascript jquery datetime momentjs datetime-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

2 个答案:

答案 0 :(得分:2)

您可以尝试使用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);

答案 1 :(得分:1)

由于您使用标记了问题,我将立即回答。

首先,弃用是因为您在不提供格式规范的情况下解析日期字符串,并且该字符串不是可以直接识别的标准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(&#34; CST&#34;有5种不同的含义)。如果您需要将其解释为-08:00,那么您必须自行完成一些字符串替换。

幸运的是,它会显示(至少根据您的要求)您根本不想要任何时区转换,因此上述代码将完成这项工作。