简体   繁体   中英

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. eg 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

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!

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM