zeid10
zeid10

Reputation: 541

Why do I get unexpected hour when substracting two times

I have this simple function to subtract time: the input values are:

$current = '23:48:32';
$arrival = '23:41:48';

$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
$waitingTime = $time; // 21:06:44

Looks like the diff for the minutes is correct, I am not sure why I am getting the 21 in front of the minutes. It should be 00:06:44. Any help is appreciated. Thank you.

Upvotes: 1

Views: 78

Answers (4)

ops
ops

Reputation: 2049

This code echo 00:06:44!

$current='23:48:32';
$arrival='23:41:48';

$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
echo $time;//00:06:44

What exactly is your problem?

Upvotes: 1

DevZer0
DevZer0

Reputation: 13525

You can't expect this code to give you an interval.

the strtotime($current) - strtotime($arrival) line calculates a interval in seconds but when you pass it to date it assumes your speaking of an interval since epoch. so you get timezone translated value for $time; you must have gotten 9 because your probably behind UTC

use strtotime($current) - strtotime($arrival) / 3600 for hours and remainder divide by 60 for minutes. and then seconds

Upvotes: 2

BlitZ
BlitZ

Reputation: 12168

That's why PHP has DateTime & DateIntervals:

<?php
header('Content-Type: text/plain; charset=utf-8');

$current = '23:48:32';
$arrival = '23:41:48';

$current = DateTime::createFromFormat('H:i:s', $current);
$arrival = DateTime::createFromFormat('H:i:s', $arrival);

$diff = $current->diff($arrival);

unset($current, $arrival);

echo $diff->format('%H:%I:%S');
?>

Output:

00:06:44

Upvotes: 1

Jm Verastigue
Jm Verastigue

Reputation: 398

try using gmdate()

$time = gmdate( "H:i:s", strtotime($current) - strtotime($arrival));

Upvotes: 4

Related Questions