如何比较momentJS忽略年份值的两个日期?

贾斯汀

假设一个学期从2015年11月1日开始到2016年1月3日。要比较的示例日期如下('YYYY-MM-DD'):

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达到此结果吗?

斯蒂芬·多克豪(Stefan Dochow)

它将像这样工作: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'));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章