View Single Post
Old 01-17-2008, 02:12 PM   #2 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Quote:
Originally Posted by Aaron View Post
I need to find a way to calculate the time elapsed between two timeestamps
A timestamp is literally just an integer of the number of seconds since midnight on January 1st 1970. To calculate the difference you can just do a simple subtraction to get the number of seconds difference between the two timestamps. If you want the result to be in another unit (minutes, days, weeks, etc.) then you can just scale that difference in seconds appropriately.

For example:
PHP Code:
<?php

$iTimeStart 
1200556800// 17 Jan 2008, 8:00am UTC (GMT)
$iTimeStop  1200643200// 18 Jan 2008, 8:00am UTC (GMT)

// abs() is used here to make sure the result
// is always a positive (well, unsigned) integer
$iTimeDiff  abs($iTimeStart $iTimeStop);

// The difference between 17 Jan 2008, 8:00am UTC and 18 Jan 2008, 8:00am UTC is 86400 seconds.
printf(
    
'The difference between <em>%s</em> and <em>%s</em> is <em>%s seconds</em>.',
    
date('d M Y, g:ia e'$iTimeStart),
    
date('d M Y, g:ia e'$iTimeStop),
    
$iTimeDiff
);
Quote:
Originally Posted by Aaron View Post
and execute an action when that time exceeds another time.
All that we need to do here is to check if the difference between the two timestamps is greater than whatever the time 'limit' is (in seconds).

PHP Code:
$iTimeLimit 12 60 60// 12 hours = 12 * 60 * 60 seconds
$iTimeNow   time();
$iTimeThen  strtotime('-1 day');

// *should* say "Yes, 1 day is..."
if ($iTimeNow $iTimeThen $iTimeLimit)
{
    echo 
'Yes, 1 day is longer than 12 hours!';
}
else
{
    echo 
'Well done, you can bend the timeline!';

Quote:
Originally Posted by Aaron View Post
I also need to find a way to add time to it.
Adding time is just as easy, in fact maybe even easier depending on the route that you wish to take. You can simple add seconds onto the timestamp integer, or you can make use of the strtotime function (much like you can with taking time away, as in the previous example).

PHP Code:
$iTimeNow time();
$iTimeAdd $iTimeNow 86400// Add 8,400 seconds (one whole day) to now
echo 'New time is 'date('d M Y, g:i:sa e'$iTimeAdd);

$iTimeAdd strtotime('+1 day'$iTimeNow); // Again, add one whole day to now
echo 'New time is 'date('d M Y, g:i:sa e'$iTimeAdd); 
Hope that provided a starting point (or at least, didn't miss the mark completely!).
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
Aaron (01-18-2008)