Skip to content

Instantly share code, notes, and snippets.

@vihatsoft
Last active June 28, 2021 13:28
Show Gist options
  • Save vihatsoft/3f240a7decd78f068447c886f3835b36 to your computer and use it in GitHub Desktop.
Save vihatsoft/3f240a7decd78f068447c886f3835b36 to your computer and use it in GitHub Desktop.
PHP get two timestamp difference in years, months, days, hours, minutes and second
<?php
// Function to get difference of two timestamp into years, months, days, hours, minutes and seconds
function getTimeDifference($datetime1, $datetime2, $inShort = true) {
$datetime1 = new DateTime(date('Y-m-d H:i:s', $datetime1));//start time
$datetime2 = new DateTime(date('Y-m-d H:i:s', $datetime2));//end time
$interval = $datetime1->diff($datetime2);
$formats_array = array( "years" => "%Y", "months" => "%m", "days" => "%d", "hours" => "%H", "minutes" => "%i", "seconds" => "%s" );
$return_time = "";
foreach($formats_array as $key => $value ) {
$int_time = $interval->format($value);
if($int_time > 0) {
$return_time .= $interval->format($value). " ".$key .", ";
if($inShort) break;
}
}
return trim(trim(trim($return_time), ","));
}
// Show the date after conversion
// 01 years, 2 months, 30 days, 23 hours, 49 minutes, 11 seconds
echo "<h2>In Long:</h2>";
echo getTimeDifference('1584817934', '1624302085', false); //true = for get in short , false = for get in long
echo "<h2>In Short:</h2>";
echo getTimeDifference('1584817934', '1624302085', true); //true = for get in short , false = for get in long
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment