如何将此日期“太平洋标准时间 2016 年 3 月 9 日星期三 09:48:09”转换为“YYYY-MM-DD HH:

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

本文关键字:HH 星期三 YYYY-MM-DD 转换 日期 太平洋 标准时间 2016      更新时间:2023-09-26

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

试图使用时刻,但它给了我一个警告。

"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);

既然你用时刻标记了你的问题,我将用时刻来回答。

首先,弃

用是因为您在不提供格式规范的情况下解析日期字符串,并且该字符串不是时刻可以直接识别的标准 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实际上并没有解释时区缩写,因为歧义太多("CST"有5种不同的含义)。 如果您需要将其解释为 -08:00 ,那么您必须自己进行一些字符串替换。

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