使用momentjs,我如何判断2个时刻是否代表同一天(不是,必然,同一时间)? [英] With momentjs, how do I tell if 2 moments represent the same day (not, necessarily, the same time)?

查看:1115
本文介绍了使用momentjs,我如何判断2个时刻是否代表同一天(不是,必然,同一时间)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个momentjs对象, moment1 moment2





为什么 moment1.isSame(moment2,'date')返回false ??



我的理解是检查 moment1.isSame(moment2,'day')返回它们是否是同一天的一周(至少,它是从文档中看起来的样子)。因此,如果'day'和'date'都不起作用,那么确定2个日期是否代表同一天的正确方法是什么?



我本可以发誓我过去曾使用 moment1.isSame(moment2,'date'),但我必须记错...

解决方案

您可以同时使用'day''date' isSame



作为 docs 说:


检查片刻是否与另一时刻相同。



当包含第二个参数时,它将匹配所有等于或大于的单位。传入将检查。传入将检查



喜欢时刻#isAfter 时刻#isBefore 时刻支持时刻#startOf 支持的任何时间单位#isSame


startOf


注意: 时刻#startOf('date')作为 2.13中的日期别名添加.0


这是一个带有最新版本( 2.17.1 )的工作示例:



  var moment1 = moment('01 / 23/17','MM / D / YYYY'); var momen t2 =时刻('01 / 23/17','MM / D / YYYY'); console.log(moment1.isSame(moment2,'day')); // trueconsole.log(moment1.isSame(moment2,'date')); // true  

 < script src =// cdnjs .cloudflare.com / AJAX /库/ moment.js / 2.17.1 / moment.min.js>< /脚本>  


I have 2 momentjs objects, moment1 and moment2:

Why is moment1.isSame(moment2, 'date') returning false??

My understanding is that checking moment1.isSame(moment2, 'day') returns whether they are the same day of the week (at least, that's what it looks like from the docs). So if both 'day' and 'date' don't work, what is the correct way to determine if the 2 dates represent the same day?

I could have sworn I've used moment1.isSame(moment2, 'date') in the past, but I must be remembering incorrectly...

解决方案

You can use both 'day' and 'date' to isSame.

As the docs says:

Check if a moment is the same as another moment.

When including a second parameter, it will match all units equal or larger. Passing in month will check month and year. Passing in day will check day, month, and year.

Like moment#isAfter and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isSame.

In the docs of startOf:

Note: moment#startOf('date') was added as an alias for day in 2.13.0

Here a working example with the lastest version (2.17.1):

var moment1 = moment('01/23/17', 'MM/D/YYYY');
var moment2 = moment('01/23/17', 'MM/D/YYYY');
console.log( moment1.isSame(moment2, 'day') ); // true
console.log( moment1.isSame(moment2, 'date') ); // true

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

这篇关于使用momentjs,我如何判断2个时刻是否代表同一天(不是,必然,同一时间)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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