Reputation: 14575
How can I subtract an older date 2010-10-18 07:44:53
from a newer date using PHP?
Upvotes: 1
Views: 589
Reputation: 23261
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!
Upvotes: 0
Reputation: 2449
I would advise working with timestamps. subtract one from the other, the difference is seconds, then simple logic to convert it to mins/hours/days ect.
you can use date, strtotime, mktime to get a timestamp
Upvotes: 1
Reputation: 16714
date_diff
http://php.net/manual/en/function.date-diff.php
If you are using DateTime objects the method is diff
Upvotes: 0