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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With