day difference between two dates code example

Example 1: javascript difference between two dates

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

Example 2: javascript date between two dates

// `min`, `max` and `date` are `Date` instances
const isBetween = (date, min, max) => (date.getTime() >= min.getTime() && date.getTime() <= max.getTime());

Example 3: How to calculate the difference between two dates

$datetime1 	= new DateTime('2020-10-11 16:52:52');
$datetime2 	= new DateTime('2020-10-13 16:52:52');
$interval 	= $datetime1->diff($datetime2);

echo $interval->format('%a days');

Example 4: get days between two dates

// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format (which does no error checking)
function parseDate(str) {
    var mdy = str.split('/');
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

alert(datediff(parseDate(first.value), parseDate(second.value)));

Example 5: difference between two dates efcore

(EndDate.Date - StartDate.Date).Days //int

Tags:

Misc Example