Thursday, June 10, 2010

Using floor and time to calculate number of days elapsed from UNIX timestamp


Finding out the number of days elapsed from a UNIX timestamp is actually pretty straightforward. If you only know two dates then first you’ll need to convert the date to a UNIX timestamps and then subtract the most recent timestamp from the older timestamp like this:
$old_timestamp = 1102971600;
$elapsed_seconds = time() - $old_timestamp;
print ‘Seconds elapsed since ‘ . date(“m-d-Y H:i:s”,$old_timestamp) . “: $elapsed_seconds”;
?>

Now, let’s convert those seconds to days using the floor() function, by just adding the following code to the code above:
/*
divide #seconds by 60 for minutes
divide #of minutes by 60 for hours
divide #of hours by 24 for days
use floor to get integer for day
*/
$elapsed_days = floor(($elapsed_seconds / 60) / 60 / 24);
print “
Number of days elapsed: $elapsed_days”;

No comments:

Post a Comment