I am using MomentJs in a ReactJs project. I am trying to compare the date and time How can I compare the time. use the remindTime object
Im am currently doing the follow however does not work because it is looking at the remindTime object and not the date and time
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,
}
Basically I want to know if the current time is great or equal to the date and time in the remindTime object
I think you can use [moment query functions]:https://momentjs.com/docs/#/query/
Take into account that moment works with specific param formats, so you cannot give it standalone objects.
Considered that, you'll need the diff function and parse apropiately remindTime.date and remindTime.time:
To get the difference in milliseconds, use moment#diff like you would use moment#from.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
And to get the difference in another unit of measurement, pass that measurement as the second argument.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
An example for this could be:
//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
Also it could be easier to think that diff is a kind of minus operator:
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0
Hope it works, for further info please check this out: https://momentjs.com/docs/#/query/