Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immitate PHP 5.3 DateTime in PHP 5.2

I was playing with the DateTime object in PHP 5.3 on my local machine and made something useful but my host (NFS) is only running 5.2 and doesn't plan to upgrade until 5.3.1 is out.

So my question is, is this code possible using 5.2? Specifically, DateTime::getTimestamp doesn't exist in 5.2

The nicetime.php include is similar to the one here http://cz2.php.net/manual/en/function.time.php#89415 basically it just outputs how long until/ago a timestamp is)

include('include/nicetime.php');

if(isset($_GET['hour']) && isset($_GET['min']) && isset($_GET['AP']) && isset($_GET['TZ'])){
    if($_GET['AP'] == 'PM'){
        $reqHour = $_GET['hour']+12;
    }else{
        $reqHour = $_GET['hour'];
    }

    $reqHour = ($_GET['AP'] == 'PM' ? $_GET['hour']+12 : $_GET['hour']);
    $reqMin = ($_GET['min'] == 0 ? '00': $_GET['min']);

    date_default_timezone_set($_GET['TZ']); 
    $reqDate = date_create($reqHour.':'.$reqMin);

    echo '<h3>'.nicetime($reqDate->getTimestamp()).'</h3>';
}

?>

If you're wondering what the point of it is, a user wants to know how long until a certain time in a timezone different than they are in. Eg, when is it 9PM in England? 2 hours from now.

like image 672
aland Avatar asked Sep 02 '09 17:09

aland


1 Answers

The last line would have to be translated to

echo '<h3>' . $reqDate->format('U') . '</h3>';

in order to work with PHP 5.2. Other that that, it looks fine.

Edit: You could subclass DateTime to provide a forwards compatible solution:

class MyDateTime extends DateTime {
    public function getTimestamp() {
         return method_exists('DateTime', 'getTimestamp') ? 
             parent::getTimestamp() : $this->format('U');
    }
}
like image 73
Øystein Riiser Gundersen Avatar answered Oct 23 '22 18:10

Øystein Riiser Gundersen