关于 javascript:moment js 在 24 小时格式的情况下返回”无效日期”

moment js returning 'invalid date ' in case of 24 hour format

考虑以下情况:

1
2
let record ="2020-04-01 13:33 PM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");

以上代码返回无效日期。

但是对于以下情况:

1
2
let record ="2020-04-01 2:33 AM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");

它返回:
2020 年 4 月 1 日上午 8:33

沙盒链接:https://codesandbox.io/s/happy-volhard-m1c7d

有什么解决这个问题的建议吗?


如果您要解析的字符串不是 moment.js 支持的格式之一并且您没有提供格式,它将使用内置的解析器代替。您将在控制台中收到一条消息,警告您这是一个坏主意(因为它是,请参阅为什么 Date.parse 给出不正确的结果?)。

当您有任何不支持的格式字符串时,您必须提供格式,例如

1
2
3
4
5
6
7
8
9
10
let s ="2020-04-01 13:33 PM UTC";

// Provide the input format when parsing
let d = moment(s, 'YYYY-MM-DD HH:mm A UTC');

// Provide the output format when formatting
console.log(d.format('MMM Do, YYYY h:mm A'));

// If the date is to be treated as UTC, use .utc
console.log(d.utc().format('MMM Do, YYYY h:mm A'));
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js">

顺便说一句,当使用 24 小时制时,使用 AM 和 PM 是多余的(并且可能会造成混淆)。


您提供的 UTC 不正确,请将 MMM Do, YYYY h:mm A 更改为 MMM Do, YYYY hh:mm A 或先将时间更改为 12 小时格式。格式预计为 01、11、24 等。