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
有什么解决这个问题的建议吗?
- 为什么你会有 13:33 AM … 因为 13:33 是 1:33 PM?
- UTC 不正确
- 另外,对于 24 小时制,使用 H:mm 而不是 h:mm A – 并确保您的输入是 24 小时制
- 抱歉应该是错误,让记录 = ‘2020-04-01 13:54 PM UTC’
如果您要解析的字符串不是 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 // Provide the output format when formatting // If the date is to be treated as UTC, use .utc |
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 等。
来源:https://www.codenong.com/61004912/