0
Q:

javascript difference between two dates in days

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
console.log(getDifferenceInDays(date1, date2));
console.log(getDifferenceInHours(date1, date2));
console.log(getDifferenceInMinutes(date1, date2));
console.log(getDifferenceInSeconds(date1, date2));

function getDifferenceInDays(date1, date2) {
  const diffInMs = Math.abs(date2 - date1);
  return diffInMs / (1000 * 60 * 60 * 24);
}

function getDifferenceInHours(date1, date2) {
  const diffInMs = Math.abs(date2 - date1);
  return diffInMs / (1000 * 60 * 60);
}

function getDifferenceInMinutes(date1, date2) {
  const diffInMs = Math.abs(date2 - date1);
  return diffInMs / (1000 * 60);
}

function getDifferenceInSeconds(date1, date2) {
  const diffInMs = Math.abs(date2 - date1);
  return diffInMs / 1000;
}
7
function dateDiffInDays(date1, date2) {
    // round to the nearest whole number
    return Math.round((date2-date1)/(1000*60*60*24));
}
var daysDiff=dateDiffInDays(new Date('December 21, 2019 03:24:00'), new Date('December 25, 2019 03:24:00')); //4 days till XMAS
4
var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
1
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');

//Difference in number of days
moment.duration(given.diff(current)).asDays();
1
// `min`, `max` and `date` are `Date` instances
const isBetween = (date, min, max) => (date.getTime() >= min.getTime() && date.getTime() <= max.getTime());
3
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");
0
/* difference between date1 and date2 in days (date2 - date1) */
/* date1 and date 2 are already javascript date objects */
function dateDifference(date2, date1) {
    const _MS_PER_DAY = 1000 * 60 * 60 * 24;

    // Discard the time and time-zone information.
    const utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
    const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());

    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
2
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

// Example
diffDays(new Date('2014-12-19'), new Date('2020-01-01'));   // 1839
1

New to Communities?

Join the community