justinw
justinw

Reputation: 710

How to compare two dates with momentJS ignoring the year value?

Let's say a term starts from 1 November 2015 to 3 January 2016. The sample dates to compare are as follows ('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)

Is there a way that I can achieve this result with MomentJS?

Upvotes: 2

Views: 1463

Answers (2)

Shashank
Shashank

Reputation: 13869

It's possible using isBetween, but kind of messy.

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);
}

The reason I'm adding a year as an optional check is just for the January case since January of 2015 is obviously not between November 2015 and January 2016. I know it's kind of hacky, but I couldn't think of any simpler way of doing it.

Upvotes: 2

Stefan Dochow
Stefan Dochow

Reputation: 1454

It would work like this: 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'));
}

EDIT: with a tiny change it would even work, if the upper boundary was not one but two (or more) years ahead from the lower one.

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'));
}

Upvotes: 0

Related Questions