繁体   English   中英

在 24 小时格式的情况下,时刻 js 返回“无效日期”

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

考虑以下情况:

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

上面的代码返回无效日期。

但是对于以下情况:

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 给出不正确的结果? )。

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

 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'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

顺便说一句,当使用 24 小时制时,使用 AM 和 PM 是多余的(并且可能令人困惑)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM