Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference using strtotime

Tags:

php

This shouldn't be hard, but still I don't understand what is happening.

<?php
    echo date( 'H:i', strtotime( '09:00' ) - strtotime( '08:00' ) ); 
    // returns 02:00 instead of 01:00

    echo date( 'H:i', strtotime( '18:45' ) - strtotime( '17:15' ) ); 
    // returns 02:30 instead of 01:30

    echo date( 'H:i', strtotime( '17:00' ) - strtotime( '09:00' ) );
    // returns 09:00 instead of 08:00

What is adding the extra hour?

So maybe I need to add a date?

<?php
    echo date( 'H:i', strtotime( '22-09-2016 17:00:00' ) - strtotime( '22-09-2016 09:00:00' ) );
    // still 09:00 instead of 08:00

Some extra information

I am using Laravel en tested in Xampp.

In Laravel /config/app.php 'timezone' => 'Europe/Amsterdam',

In Xampp date_default_timezone_set('Europe/Amsterdam');

Still no difference.

This calculation is done in the blade template where I cannot access the DateTime class.

I found a way to use the DateTime class. Another solution was changing the timezone to UTC, but then all my other timestamps are wrong.

like image 370
Ron van der Heijden Avatar asked Sep 22 '16 09:09

Ron van der Heijden


2 Answers

find difference using DateTime object like

$time1 = new DateTime('18:45');
$time2 = new DateTime('17:15');
$interval = $time1->diff($time2);
echo $interval->format('%H:%I');
like image 182
Rakesh Sojitra Avatar answered Sep 22 '22 14:09

Rakesh Sojitra


As a purely variety alternative to the method posted by Rakesh, because you're looking at only time values rather than date values you don't need the [slight] overhead that strtotime generates by converting everything to unix timestamps. you also don't need to worry about time zones, as it's a purely mathematical operation.

function minutes_from_time($time){
    $parts = explode(":",$time);
    $minutes = ($parts[0] * 60) + $parts[1];
    return $minutes;
}

$timeLapsed = minutes_from_time("09:00") - minutes_from_time("08:00");

/***
 Format into H:i
 ***/
 $hours = floor($timeLapsed/60);
 $minutes = $timeLapsed - ($hours * 60);
 $minutes = sprintf("%02d", $minutes); //force 2 digit minutes.
 $hours = sprintf("%02d",  $hours); //force 2 digit hours.

 $result = $hours.":".$minutes;   

You may need to handle some special cases of times crossing over midnight, but....

If in the future you do want to include dates and/or time zone data then definitely go with using the DateTime class as recommended by myself and others.

like image 28
Martin Avatar answered Sep 20 '22 14:09

Martin