首页 > 解决方案 > 比较两个日期和时间时显示“无效日期”

问题描述

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

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 文件

标签: javascriptreactjsmomentjs

解决方案


尝试使用数组而不是字符串对日期进行排序。moment([2021, 4, 19, 8, 30, 0])因为他们也在文档中这样做。我已经在您的代码盒中对其进行了测试,并且可以正常工作:)

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

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


推荐阅读