sevenWonders
sevenWonders

Reputation: 185

Subtract time in php. Strange results

echo date('H:i', time()); // 10:15    
echo date('H:i', strtotime($this->deadline)); // 10:05
$delay = time() - strtotime($this->deadline);
echo date('H:i', $delay); // 02:10 

Why delay is 2 hours 10 min instead of 10 min?

I assume it has something to do with timezone. Now it's Europe/Helsinki. But how can I get just an absolute difference between two timestamps?

EDIT

echo time(); // 1339745334
echo strtotime($this->deadline); // 1339657500

Upvotes: 0

Views: 114

Answers (3)

Corsair
Corsair

Reputation: 1044

If you want to display the real time you will need to format the time accourding to the difference. Here an example function which you can extend as you wish:

function time_diff($format,$seperator,$delay){

    $days = floor($delay/86400);
    $hours = floor(($delay%86400)/3600);
    $mins = floor(($delay%3600)/60);
    $secs = floor(($delay%60));

    $format = explode($seperator,$format);
    $return = "";

    foreach($format as $value){

        if(strlen($return) > 0){
            $return .= $seperator;
        }

        switch($value){
            case 'H':{
                $return .= $hours;
                break;
            }
            case 'i':{
                $return .= $mins;
                break;
            }
            case 'z':{
                $return .= $days;
                break;
            }
            case 's':{
                $return .= $secs;
                break;
            }
        }

        return $return;                    
    }

Usage: function_time_diff("H:i",':',$delay) => Your delay formatted.

Upvotes: 0

vicky
vicky

Reputation: 705

Try this code

date_diff($time_start, $time_ends);

function date_diff($d1, $d2){
        $d1 = (is_string($d1) ? strtotime($d1) : $d1);
        $d2 = (is_string($d2) ? strtotime($d2) : $d2);
        $diff_secs = abs($d1 - $d2);
        $base_year = min(date("Y", $d1), date("Y", $d2));
        $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
        return array(
            "years" => date("Y", $diff) - $base_year,
            "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
            "months" => date("n", $diff) - 1,
            "days_total" => floor($diff_secs / (3600 * 24)),
            "days" => date("j", $diff) - 1,
            "hours_total" => floor($diff_secs / 3600),
            "hours" => date("G", $diff),
            "minutes_total" => floor($diff_secs / 60),
            "minutes" => (int) date("i", $diff),
            "seconds_total" => $diff_secs,
            "seconds" => (int) date("s", $diff)
        );
    }

Upvotes: 0

J A
J A

Reputation: 1766

$delay is not actually a proper timestamp. It's just the difference between two timestamps, which could be as low as 1. mktime() function could be useful here.

Upvotes: 1

Related Questions