javascript - 比较两个日期和时间时显示“无效日期”
问题描述
在比较两个日期和时间时,我想留出时间。我已经使用矩库将当前日期时间对格式化为即将到来的日期时间对。请参见下面的示例:
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 文件
解决方案
尝试使用数组而不是字符串对日期进行排序。moment([2021, 4, 19, 8, 30, 0])
因为他们也在文档中这样做。我已经在您的代码盒中对其进行了测试,并且可以正常工作:)
https://momentjs.com/docs/#/displaying/difference/
这是修复:https ://codesandbox.io/s/material-demo-forked-kh7os?file=/timediff.js
推荐阅读
- react-native - TabNavigator : 直接进入屏幕
- bluetooth - 我应该使用什么模型来表示蓝牙网格中的值数组?
- javascript - 如何进行 Api 获取并显示结果
- mysql - SQL:将一列从一个表移动到另一个
- java - 静态导入重载方法
- python - 有没有办法使用 pafy 从播放列表中获取 YT url 或视频 ID?
- llvm - setCleanup 方法在 LandingPad 上做了什么?
- php - PHP 以一毫秒回显日期
- json - 将 json 对象中的元素数组保存到不同的行中
- python - 如何创建不可变对象的副本并更新一些属性?