使用Moment.js比较时间 [英] Comparing Times Using Moment.js

查看:4414
本文介绍了使用Moment.js比较时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 Moment.js ,我遇到了一个问题。我一直在试图确定给出的日期是否在过去或将来。日期存储为 Unix时间戳。所以当我将未来的日期与当前日期进行比较时,它的工作正常,但是在过去的日期中并不会触发。示例代码如下,小提琴在这里

I've been playing around with Moment.js and I've come across a problem. I've been trying to identify whether a date given is in the past or in the future. The dates are stored as Unix timestamps. So when I'm comparing future dates with current dates, it's working ok, but it's not triggering for past dates. The sample code is below and a fiddle is here.

var pastUnixTime = '1348812970'; //some time in the past
var futureUnixTime = '1352350231';

if (moment.unix(futureUnixTime).format('DD MM YYYY') > moment().format('DD MM YYYY')) {
    console.log('yay');
}


if (moment.unix(pastUnixTime).format('DD MM YYYY') < moment().format('DD MM YYYY')) {
    console.log('yay 2');
}
​

上面的代码记录 yay 不是 yay 2 。任何人都可以向我解释为什么不记录 yay 2

The above code logs yay not not yay 2. Can anybody explain to me why is it not logging yay 2?

推荐答案

您实际上不需要使用 .format()

首先,时间戳应该是数字,而不是字符串(例如, var pastUnixTime = 1348812970; ),其次可以直接比较:

First, the timestamps should be numbers, not strings (ex, var pastUnixTime = 1348812970;), and second, you can compare them directly:

> pastUnixTime = 1348812970;
> pastUnixTime < moment().unix()
true
> pastUnixTime > moment().unix() 
false

现在,代码失败的原因是当您比较 DD MM YYYY 字符串时,他们正在进行字典比对...而这些日子是第一个!所以字符串01 01 2000永远是小于31 12 1900。如果您想要比较字符串,您可以使用 YYYY MM DD 格式 - 这样,2000 01 01将正确地大于1900 12 31。但是没有理由这样做 - 时间戳更直接。

Now, the reason your code is failing is that when you compare the DD MM YYYY strings, they are being compared lexicographically… And the days are first! So the string "01 01 2000" will always be "less than" "31 12 1900". If you wanted to compare strings, you could use YYYY MM DD format — that way, "2000 01 01" will be correctly "greater than" "1900 12 31". But there's no reason to do that - timestamps are much more straight forward.

最后,一个注释:你实际上并不需要使用 .unix() - moment()的实例将明智比较:

Finally, a note: you don't actually need to use the .unix() - instances of moment() will compare sensibly:

> past = moment().subtract("days", 1)
> now = moment()
> past < now
true
> past > now
false

这篇关于使用Moment.js比较时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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