0

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?

Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36
  • 1
    Does this answer your question? [Epoch is not epoch if do a new Date(0L). Why?](https://stackoverflow.com/questions/2434557/epoch-is-not-epoch-if-do-a-new-date0l-why) – Jeto Nov 15 '20 at 10:43
  • 1
    ^ this is not a PHP question but it's the same answer. Basically, `date('h:i:s', 0)` will not always return 00:00:00, because it depends on your timezone. – Jeto Nov 15 '20 at 10:44

2 Answers2

2

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

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
SK Shewa
  • 106
  • 1
  • 9
1

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.
Ro Achterberg
  • 2,504
  • 2
  • 17
  • 17