Time difference using strtotime

It should not be difficult, but still I do not 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 adds an extra hour?

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

Additional 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 server template, where I cannot access the DateTime class.

I found a way to use the DateTime class. Another solution changed the time zone to UTC, but then all my other timestamps are wrong.

+4
source share
3 answers

find the difference using a DateTime object like

$time1 = new DateTime('18:45');
$time2 = new DateTime('17:15');
$interval = $time1->diff($time2);
echo $interval->format('%H:%I');
+5
source

, Rakesh, , , [ ], strtotime , unix. , .

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;   

, ....

/ , DateTime .

+3

The problem with time zones.

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::difffor proper operation

+2
source

Source: https://habr.com/ru/post/1655447/


All Articles