首页 > 解决方案 > 如何使用 MomentJs 和 React 比较日期和时间

问题描述

我在 ReactJs 项目中使用 MomentJs。我正在尝试比较日期和时间如何比较时间。使用提醒时间对象

我目前正在执行以下操作但不起作用,因为它正在查看提醒时间对象而不是日期和时间

moment() >= moment(remindTime) ? true : false
const remindTime =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2021-09-26', time: '7:43:21 pm' },
            isComplete: false,
        }

基本上我想知道当前时间是否大于或等于提醒时间对象中的日期和时间

标签: javascriptmomentjs

解决方案


我认为您可以使用[时刻查询功能]:https ://momentjs.com/docs/#/query/

考虑到那一刻适用于特定的参数格式,所以你不能给它独立的对象。

考虑到这一点,您将需要该diff函数并进行适当的解析 remindTime.date,并且remindTime.time

要获得以毫秒为单位的差异,请像使用 moment#from 一样使用 moment#diff。

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

为了获得另一个度量单位的差异,将该度量作为第二个参数传递。

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

一个例子可能是:

//given
const remindTime1 =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2021-09-26', time: '7:43:21 pm' },
            isComplete: false,
        }
// and also given another object for comparing times and dates

const remindTime2 =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2020-09-28', time: '9:50:21 pm' },
            isComplete: false,
        }

const parseDate1= remindTime.remindTime.date.split('-');
//this returns [2021,09,28]
const parseDate2= remindTime2.remindTime.date.split('-');
//this returns [2021,09,26]

var a = moment(parseDate1);
var b = moment(parseDate2);

//then you can compare dates in different ways sush us:

a.diff(b, 'days')   // 1
a.diff(b) // 86400000 => this is miliseconds
a.diff(b, 'years');   // 1

也可以更容易地认为 diff 是一种减号运算符:

a.diff(b) // a - b < 0
b.diff(a) // b - a > 0

希望它有效,有关更多信息,请查看:https ://momentjs.com/docs/#/query/


推荐阅读