Oliver M Grech
Oliver M Grech

Reputation: 3181

Basic PHP Time calculation having a wrong answer

I have this basic PHP time calculation which just substracts between two timestamps but it's giving back an additional hour.

echo date('h:i:s',strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00'));

I am expecting the answer to be 55 min ( 00:55:00 ) Instead it gives 01:55:00

EDIT: On PHP fiddle it works fine, on my server it doesn't (and the time is set properly)

Any insight?

Upvotes: 0

Views: 64

Answers (2)

Ro Achterberg
Ro Achterberg

Reputation: 2714

Try this. See comments for explanation and output.

<?php

$from = '2020-11-15 11:05:00';
$to = '2020-11-15 12:00:00';

// 'U' gets UNIX seconds since epoch.
$fromSeconds = (new DateTime($from))->format('U');
$toSeconds = (new DateTime($to))->format('U');
$interval = $toSeconds - $fromSeconds;

// Get number of days
$days = floor($interval / 86400);
$interval -= $days * 86400;
// Get number of hours
$hours = floor($interval / 3600);
$interval -= $hours * 3600;
// Get number of minutes
$minutes = floor($interval / 60);
$interval -= $hours * 60; 

var_dump($days); // 0
var_dump($hours); // 0
var_dump($minutes); // 55

This explains what happened in your first attempt:

$seconds = strtotime('2020-11-15 12:00:00') - strtotime('2020-11-15 11:05:00');
var_dump($seconds); // 3300

// You're passing an _interval_ to date(), where it expects a timestamp
// in UNIX epoch format.
// Which means, seconds counted from UNIX time 0.
// UNIX time 0 starts at 1970-01-01 01:00:00!
// See:
echo date('Y-m-d H:i:s', 0); // 1970-01-01 01:00:00!

// Your code is formatting the TIME, not the INTERVAL of your argument.
// Which is the 1 from 01:00:00 and 55 minutes from your value.

Upvotes: 1

SK Shewa
SK Shewa

Reputation: 106

create date object by date_create() function

$date1 = date_create("y-m-d H:i:s");

$date2 = date_create("y-m-d H:i:s");

print_r(date_diff($date1-$date2));

you can get the diff of year, month , hour , min, sec

Upvotes: 2

Related Questions