2015-11-14 67 views
1

比方说,一个任期开始从2015年11月1日至3日2016年一月样品日期比较如下(“YYYY-MM-DD”):如何比较两个日期与momentJS忽略年份值?

2015-10-12 = false 
2015-11-01 = true (inclusive) 
2015-12-20 = true 
2015-01-03 = true (inclusive) 
2016-01-30 = false 
2017-11-21 = true (year is ignored) 
2010-12-20 = true (year is ignored) 

有没有一种方法,我可以做到这一点结果与MomentJS?

+0

最简单的解决办法是,以测试目标日期范围内,如果是,返回true,否则设定目标日期的年份(你可能想使用它的一个副本)到2015年,测试它是否在界限内,如果是,则返回true;否则,将年份设置为2016,如果它在范围内,则返回true,否则返回false –

+0

感谢您的反馈。当我在日历中使用它时,我会为每个用户查询多次进行比较。我只是想知道是否有另一种方式来做到这一点。 – justinw

+0

有一种使用'____-MM-DD'格式忽略年份的'anser'和'isBetween()'来比较。我想知道为什么那个人删除了他的帖子,解决方案有效。我在删除代码之前测试了代码:http://pastebin.com/NSJVRdxY – Shanoor

回答

0

它的工作是这样的: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')); 
} 
1

它可能使用isBetween,但有点混乱。

function isWithinTerm(dateString) { 
    var dateFormat = '____-MM-DD', // Ignore year, defaults to current year 
     begin = '2015-10-31', // Subtract one day from start of term 
     end = '2016-01-04', // Add one day to finish of term 
     mom = moment(dateString, dateFormat); // Store to avoid re-compute below 
    return mom.isBetween(begin, end) || mom.add(1, 'y').isBetween(begin, end); 
} 

我加入了一年作为一个可选的检查原因只是以来的2015年1月的月情况显然不是2015年11月和2016年一月间,我知道这是一种哈克,但我不能”没有想到任何更简单的方法。

+0

感谢您指出'__'语法在momentJS。直到现在我还没有意识到,在我的其他日期操作中可能会有用:) – justinw