calculate date and time difference code example

Example 1: 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 2: date difference

function daysBetween(first, second) {

    // Copy date parts of the timestamps, discarding the time parts.
    var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
    var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());

    // Do the math.
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var millisBetween = two.getTime() - one.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    return Math.floor(days);
  
  // it will return date difference in days 
}

Example 3: calculate total time from start and end datetime

var date1 = new Date('2019-02-27T23:34:25');
var date2 = new Date('2019-02-28T15:55:38');
var ElapsedSeconds = (date2 - date1) / 1000;
// var ElapsedHours = ElapsedSeconds / 3600;

Tags:

Vb Example