它的工作是这样的:https://jsfiddle.net/3xxe3Lg0/
var moments = [
'2015-10-12',
'2015-11-01',
'2015-12-20',
'2015-01-03',
'2016-01-30',
'2017-11-21',
'2010-12-20'];
var boundaries = [moment('2015-11-01').subtract(1, 'days'),moment('2016-01-03').add(1, 'days')];
for (var i in moments){
res = moments[i] + ': ';
if (
moment(moments[i]).year(boundaries[0].year()).isBetween(boundaries[0], boundaries[1]) ||
moment(moments[i]).year(boundaries[1].year()).isBetween(boundaries[0], boundaries[1])
){
res += 'true';
}
else{
res += 'false';
}
$('<div/>').text(res).appendTo($('body'));
}
编辑:有一个微小的变化它甚至会从下一个工作,如果上边界是不是一个而是两个(或更多)未来几年。
for (var i in moments){
res = moments[i] + ': ';
if (
moment(moments[i]).year(boundaries[0].year()).isBetween(boundaries[0], boundaries[1]) ||
moment(moments[i]).year(boundaries[0].year()+1).isBetween(boundaries[0], boundaries[1])
){
res += 'true';
}
else{
res += 'false';
}
$('<div/>').text(res).appendTo($('body'));
}
最简单的解决办法是,以测试目标日期范围内,如果是,返回true,否则设定目标日期的年份(你可能想使用它的一个副本)到2015年,测试它是否在界限内,如果是,则返回true;否则,将年份设置为2016,如果它在范围内,则返回true,否则返回false –
感谢您的反馈。当我在日历中使用它时,我会为每个用户查询多次进行比较。我只是想知道是否有另一种方式来做到这一点。 – justinw
有一种使用'____-MM-DD'格式忽略年份的'anser'和'isBetween()'来比较。我想知道为什么那个人删除了他的帖子,解决方案有效。我在删除代码之前测试了代码:http://pastebin.com/NSJVRdxY – Shanoor