【问题标题】:Showing 'Invalid Date' when comparing two dates and times in moment比较两个日期和时间时显示“无效日期”
【发布时间】:2021-07-13 17:26:37
【问题描述】:

我想在比较两个日期和时间时留出时间。我已经使用矩库将当前日期时间对格式化为即将到来的日期时间对。请参阅下面的示例:

var now = moment().format("Do MMM YYYY, h:mm A"); {/* <-- Current date-time pair */}

var newTime = "19th Apr 2021 9:30 PM";            {/* <-- Coming date-time pair */}

var duration = moment.utc(moment(now, "Do MM YYYY, h:mm A").diff(moment(newTime, "Do MM YYYY, h:mm A")))
               .format("h:mm");

return (
        <>
        {
           console.log('Time Left', duration)
        }
        </>
)

在控制台中收到错误为“无效日期”

什么是适当的解决方案,在两个日期时间之间留出时间?

以下是 CodeSandbox 链接:https://codesandbox.io/s/material-demo-forked-sn31v

点击链接后,前往 timediff.js 文件

【问题讨论】:

  • 您的日期格式字符串不一致,请将 MM 替换为 MMM - 更好地创建单个格式字符串变量并使用它而不是多次键入/复制字符串
  • 另外,没有理由将now 转换为字符串然后再次解析。

标签: javascript reactjs momentjs


【解决方案1】:

尝试使用数组而不是字符串来排列日期。 moment([2021, 4, 19, 8, 30, 0]) 因为他们也在文档中这样做。我已经在你的代码盒中测试过了,它可以工作:)

https://momentjs.com/docs/#/displaying/difference/

这里是修复:https://codesandbox.io/s/material-demo-forked-kh7os?file=/timediff.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多