drewwyatt
drewwyatt

Reputation: 6027

How to compare dates in Javascript without using year?

The title says it all. I'm using MomentJS in other areas, so I am comfortable with a solution that uses moment (or not - either way is fine). In this solution, the function would return the shortest path to the compared date. e.g. comparing 12-31 to 01-01 would return 1, not 364. Basically this is what I am looking to do:

var today = '08-06'; // august 6th 
var dateOne = '09-03' // september 3rd
var dateTwo = '02-29' // february 29th
var dateThree = '01-01' // january 1st

getDifferenceInDays(today, dateOne); // => 28
getDifferenceInDays(today, dateTwo); // => -159
getDifferenceInDays(today, dateThree); // => 147

Upvotes: 0

Views: 91

Answers (2)

John Barton
John Barton

Reputation: 155

You should be able to do this pretty easily with MomentJS by getting the month and day of the month from your Date object.

var getDifferenceInDays = function(date1, date2) {
  var day1 = date1.dayOfYear();
  var day2 = date2.dayOfYear();

  if (Math.abs(day1 - day2) < (365 - Math.abs(day2 - day1))) {
    return Math.abs(day1 - day2);
  } else {
    return (365 - Math.abs(day1 - day2));
  }
}

Moment's "dayOfYear()" function returns the day of the year (a number between 1 and 366). Hope this helps!

Upvotes: 1

cjds
cjds

Reputation: 8426

This works with MomentJS. The caveat is that when you initialize MomentJS date it implicitly adds the year to this year. So, the assumption is that these values are calculated for this year

function getDifferenceInDays(date1, date2) {
  var day1 = moment(date1,'MM-DD').dayOfYear();
  var day2 = moment(date2,'MM-DD').dayOfYear();
  var diff1=(day2 - day1)
  var diff2=365- Math.abs(diff1)
  if (Math.abs(diff1)>Math.abs(diff2)) {
     return diff2;
  } else {
     return diff1;
  }
}

var today = '08-06'; // august 6th 
var dateOne = '09-03' // september 3rd
var dateTwo = '02-29' // february 29th
var dateThree = '01-01' // january 1st
console.log(";;;;")
console.log(getDifferenceInDays(today, dateOne)); // => 28
console.log(getDifferenceInDays(today, dateTwo)); // => -159
console.log(getDifferenceInDays(today, dateThree)); // => 147

http://jsfiddle.net/r2brgf4r/

Upvotes: 1

Related Questions