Created
December 14, 2018 19:19
-
-
Save iprodev/46d0626df1685ddade8be6a273d4d7ed to your computer and use it in GitHub Desktop.
PHP : Get human readable time difference between 2 dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get human readable time difference between 2 dates | |
* | |
* Return difference between 2 dates in year, month, hour, minute or second | |
* The $precision caps the number of time units used: for instance if | |
* $time1 - $time2 = 3 days, 4 hours, 12 minutes, 5 seconds | |
* - with precision = 1 : 3 days | |
* - with precision = 2 : 3 days, 4 hours | |
* - with precision = 3 : 3 days, 4 hours, 12 minutes | |
* | |
* @param mixed $time1 a time (string or timestamp) | |
* @param mixed $time2 a time (string or timestamp) | |
* @param integer $precision Optional precision | |
* @return string time difference | |
*/ | |
function get_date_diff( $time1, $time2, $precision = 2 ) { | |
// If not numeric then convert timestamps | |
if( !is_int( $time1 ) ) { | |
$time1 = strtotime( $time1 ); | |
} | |
if( !is_int( $time2 ) ) { | |
$time2 = strtotime( $time2 ); | |
} | |
// If time1 > time2 then swap the 2 values | |
if( $time1 > $time2 ) { | |
list( $time1, $time2 ) = array( $time2, $time1 ); | |
} | |
// Set up intervals and diffs arrays | |
$intervals = array( 'year', 'month', 'day', 'hour', 'minute', 'second' ); | |
$diffs = array(); | |
foreach( $intervals as $interval ) { | |
// Create temp time from time1 and interval | |
$ttime = strtotime( '+1 ' . $interval, $time1 ); | |
// Set initial values | |
$add = 1; | |
$looped = 0; | |
// Loop until temp time is smaller than time2 | |
while ( $time2 >= $ttime ) { | |
// Create new temp time from time1 and interval | |
$add++; | |
$ttime = strtotime( "+" . $add . " " . $interval, $time1 ); | |
$looped++; | |
} | |
$time1 = strtotime( "+" . $looped . " " . $interval, $time1 ); | |
$diffs[ $interval ] = $looped; | |
} | |
$count = 0; | |
$times = array(); | |
foreach( $diffs as $interval => $value ) { | |
// Break if we have needed precission | |
if( $count >= $precision ) { | |
break; | |
} | |
// Add value and interval if value is bigger than 0 | |
if( $value > 0 ) { | |
if( $value != 1 ){ | |
$interval .= "s"; | |
} | |
// Add value and interval to times array | |
$times[] = $value . " " . $interval; | |
$count++; | |
} | |
} | |
// Return string with times | |
return implode( ", ", $times ); | |
} | |
echo get_date_diff( time() - 348900, time() ); | |
// 4 days, 55 minutes | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment