How to calculate minute difference between two date-times in PHP?
Answers
Most of the answers seem focused around converting the date from a string to time. It seems you're mostly thinking about getting the date into the '5 days ago' format, etc.. right?
This is how I'd go about doing that:
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
I haven't tested that, but it should work.
The result would look like
event happened 4 days ago
or
event happened 1 minute ago
cheers
$d = new DateTime('Wed Feb 01 2012 05:00:00 GMT-080');
echo $d->format('Y-m-dTH:i:s');
time and date are both stored as numerical, decimal values (floating point actually). Dates are the whole numbers and time is the decimal part (1/24 = 1 hour, 1/24*1/60 is one minute etc...)
Date-time difference is calculated as:
date2-date1
time2-time1
which will give you the answer in days, now multiply by 24 (hours in day) and then by 60 (minutes in hour) and you are there:
time elapsed = ((date2-date1) + (time2-time1)) * 24 * 60
or
C3 = ((A3-A2)+(B3-B2))*24*60
Just set the cell to be shown in numerical format and it will show a decimal number.
The integer part corresponds to the date value (i.e. the day) and the decimal part to the time of the day.
If you multiply the numerical value of 1:45 (which is 0,07) by 24x60 (the number of hours in a day and the number of minutes in an hour) you will obtain the value in minutes of your cell (105).
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from
January 1, 1970, 00:00:00 GMT