Thursday, June 10, 2010

Performing mathematical analysis on two dates using PHP

Hi there,

I recently had to work out how much time had passed since an event had occurred in PHP and needed to do in a way that worked it out in minutes. I of course decided to use PHP's time functions to do so.

The key to making this work was of course to find out how time had passed between two references, namely now and a stored reference of time, i.e. a date time piece of information stored in a database, i.e. '2010-06-03 09:56:00'.

The first thing we have to do is find out the UNIX timestamp of the date that we are going to compare now to and this is done like so:

$reference1 = strtotime('2010-06-03 09:56:00');
/*
This function takes a typed out date time value (its first parameter) and and then returns the number of seconds that have passed since 1970-01-01 00:00:00 - aka The Unix Epoch.
*/

$reference2 = time();
/*
This again returns the number of seconds passed since the Unix Epoch.
*/

Now that we have our our two values standardised in to seconds we can perform analysis on them by using a little mathematics, like so:

//calculate difference in seconds
echo 'Seconds: '. $secondsPassed = $reference2-$reference1;

//calculate seconds to minutes
echo ' Minutes: '. $minutes = $secondsPassed/60;

//convert minutes to hours
echo 'Hours: '. $hours = $minutes/60;

//convert to days
echo 'Days: '. $days = $hours/24;

//convert to weeks
echo ' Weeks: '. $weeks = $days/7;

Of course this is only a small set of examples and you can mix and match the arithmetic to get to a more precise value in less steps. This example also doesn't round any figures, but you may wish to do so, functions like round(), ceil() and floor() would be of help, depending on the value you want to extract.

I hope that helps.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home