How can I subtract an older date 2010-10-18 07:44:53 from a newer date using PHP?
views:
42answers:
3
A:
date_diff
http://php.net/manual/en/function.date-diff.php
If you are using DateTime objects the method is diff
Diego
2010-10-18 15:48:47
PHP >= 5.3.0 only
Spilarix
2010-10-18 15:52:20
is there another way?
huf
2010-10-18 15:53:59
For an alternative, there's the answer to this question: http://stackoverflow.com/questions/676824/how-to-calculate-the-date-difference-between-2-dates-using-php
Axidos
2010-10-18 15:54:17
In the link there is the code to make the function in the case PHP < 5.3
Diego
2010-10-18 15:55:05
A:
Answering the question kind of depends on what return value you want. Seconds? Minutes? Here's a simple function you can try to get the value in any form you want:
<?php
define('SUBDATES_SECS', 0);
define('SUBDATES_MINS', 1);
define('SUBDATES_HOURS', 2);
define('SUBDATES_DAYS', 3);
define('SUBDATES_WEEKS', 4);
define('SUBDATES_MONTHS', 5);
define('SUBDATES_YEARS', 6);
function sub_dates($older, $newer, $ret = SUBDATES_SECS) {
$older = (is_numeric($older)) ? $older : strtotime($older);
$newer = (is_numeric($newer)) ? $newer : strtotime($newer);
$result = $newer - $older;
switch($ret) {
case SUBDATES_MINS:
$result /= 60;
break;
case SUBDATES_HOURS:
$result /= 120;
break;
case SUBDATES_DAYS:
$result /= 86400;
break;
case SUBDATES_WEEKS:
$result /= 604800 ;
break;
case SUBDATES_MONTHS:
$result /= 2629743;
break;
case SUBDATES_YEARS:
$result /= 31556926;
break;
}
return $result;
}
Using it:
<?php
$older = time();
sleep(3);
$newer = time();
echo sub_dates($older, $newer);
// Returns 3
echo sub_dates($older, $newer, SUBDATES_MINS);
// Returns 0.05
echo sub_dates('2010-04-19 01:01:00', '2010-04-19 01:02:00', SUBDATES_MINS);
// Returns 1
It's pretty untested though!
mellowsoon
2010-10-18 17:47:31