首页 > 解决方案 > Invalid Date error trying to parse a string containing AM or PM using npm date-and-time library in javascript

问题描述

i get invalid date error trying to parse a string containing PM or AM with time-and-date, here is my code:

const date = require('date-and-time');

let d = date.parse('Dec, 25 2019 at 3:51 AM', 'MMM, D YYYY at h:m A');

//same error with following line also
//let d = date.parse('Dec, 25 2019 at 3:51 AM', 'MMM, D YYYY at h:m AA (*)');

console.log(d);

result:

Invalid Date

i'm referencing their document here: https://www.npmjs.com/package/date-and-time/v/0.11.1

the page has following lines in the document, i wonder if I misunderstood them:

  A         meridiem    a.m., p.m.
  a (*)     meridiem    A.M., P.M.
  AA (*)    meridiem    AM, PM
  aa (*)    meridiem    am, pm

标签: javascriptdatetime

解决方案


正如@ChrisG 评论的那样,问题是您使用的是AM/PM而不是a.m./ p.m.

它在使用后者时有效,请参阅沙箱。

编辑:

如果您想使用 AM/PM,您应该在该包上创建功能请求或切换到另一个包(例如,时刻)


推荐阅读