用片刻检查日期是否从2分钟前开始 [英] Use moment to check if date is from 2 minutes ago

查看:97
本文介绍了用片刻检查日期是否从2分钟前开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了,但是我无法使其工作.

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

我有一个这样的日期数组:['5/15/2017, 2:59:06 PM', '5/15/2017, 2:59:16 PM', ...]

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

我想过滤它并获取最近2分钟的日期.

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

这就是我在做什么:

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

但这总是返回true.

我看到twoMinutesAgo是2017年5月15日星期一14:57:09 GMT-0700(PDT)

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

moment(stat.date)是2018年3月5日星期一14:59:06 GMT-0800(PST)

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));

这篇关于用片刻检查日期是否从2分钟前开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆