Ron van der Heijden
Ron van der Heijden

Reputation: 15070

Time difference using strtotime

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.

Upvotes: 6

Views: 3959

Answers (3)

Martin
Martin

Reputation: 22760

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.

Upvotes: 2

Samuel Loog
Samuel Loog

Reputation: 272

Problem with timezones.

echo date('Y-m-d H:i:s', 0); //return "1970-01-01 01:00:00";
echo date('Y-m-d H:i:s', 3601); //return "1970-01-01 02:00:01";

use DateTime::diff for correct work

Upvotes: 1

Rakesh Sojitra
Rakesh Sojitra

Reputation: 3658

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');

Upvotes: 5

Related Questions