Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use moment to check if date is from 2 minutes ago

Tags:

date

momentjs

I tried this but I can't make it work.

I have an array of dates like this: ['5/15/2017, 2:59:06 PM', '5/15/2017, 2:59:16 PM', ...]

And I want to filter it and get the dates from the last 2 minutes.

This is what I'm doing:

const twoMinutesAgo = moment().subtract(2, 'minutes')
myArray.filter(stat => moment(stat.date).isAfter(twoMinutesAgo))

but this is returning always true.

I saw that twoMinutesAgo is Mon May 15 2017 14:57:09 GMT-0700 (PDT)

while moment(stat.date) is Mon Mar 05 2018 14:59:06 GMT-0800 (PST)

But I'm not sure if that has something to do with it. Any ideas what I'm doing wrong?

like image 549
Mati Tucci Avatar asked May 15 '17 22:05

Mati Tucci


1 Answers

Part of the issue is that you're only looking at the hour of the day, but you're actually comparing absolute dates.

The other issue you have is moment isn't correctly parsing your date strings. To rectify this, you can provide a format string to instruct moment on how to parse apart the important bits:

const PARSE_FORMAT = 'M/D/YYYY, H:mm:ss A';
const twoMinutesAgo = moment().subtract(2, 'minutes')
myArray.filter(stat => moment(stat.date, PARSE_FORMAT).isAfter(twoMinutesAgo));
like image 149
André Dion Avatar answered Oct 13 '22 11:10

André Dion