Last active
August 4, 2017 21:42
-
-
Save kjbrum/0d412ddbef13aee131c3 to your computer and use it in GitHub Desktop.
Calculate the difference between two dates.
This file contains hidden or 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 | |
/** | |
* Calculate the difference between two dates. | |
* | |
* @param string $int The interval to calculate (y = years, m = months, d = days, h = hours, i = minutes, s = seconds) | |
* @param string $d1 The first date (YYYYMMDD) | |
* @param string $d2 The second date (YYYYMMDD) | |
* @param mixed $round Whether to return a decimal value, or round up or down | |
* @param boolean $absolute Whether the value should always be positive | |
* @return integer $results The calculated value | |
*/ | |
function date_difference($int, $d1, $d2, $round=true, $absolute=true) { | |
// Make sure we are working with strings | |
if(is_string($d1)) | |
$d1 = date_create($d1); | |
if(is_string($d2)) | |
$d2 = date_create($d2); | |
// Get the difference | |
$diff = date_diff($d1, $d2, $absolute); | |
// Decide what we are calculating | |
switch($int){ | |
case 'y': | |
$results = $diff->y + $diff->m / 12 + $diff->d / 365.25; | |
break; | |
case 'm': | |
$results= $diff->y * 12 + $diff->m + $diff->d/30 + $diff->h / 24; | |
break; | |
case 'd': | |
$results = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h/24 + $diff->i / 60; | |
break; | |
case 'h': | |
$results = ($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h + $diff->i/60; | |
break; | |
case 'i': | |
$results = (($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i + $diff->s/60; | |
break; | |
case 's': | |
$results = ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i)*60 + $diff->s; | |
break; | |
} | |
// Round the value if needed | |
switch($round) { | |
case 'up': | |
$results = ceil($results); | |
break; | |
case 'down': | |
$results = floor($results); | |
break; | |
case true: | |
$results = round($results); | |
break; | |
} | |
// Invert the value if needed | |
if($diff->invert) { | |
return -1 * $results; | |
} else { | |
return $results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment