user3220962 user3220962 - 3 months ago 23
PHP Question

Unexpected value returned by DateTime::diff when querying Twitch API

I have a script that should tell me for how long a certain stream on twitch has been live. The script works, but I get incorrect output. Maybe I made some mistakes with the time formats?

The

created_at
value I get looks like
2016-08-13T16:05:30Z
,
so if I calculate the difference to today (
$heute
) I should get around 0 days, 6 hours, 13 Minutes but the output I receive is 12 Tage (Days), 21 Stunden (Hours), 13 Minuten (Minutes).

For example I used this JSON: https://api.twitch.tv/kraken/streams/lirik by setting
$_GET['channel']
to
lirik
.

Here is my current code:

$url = "https://api.twitch.tv/kraken/streams/" . $_GET['channel'];

$result = file_get_contents($url);
$result = json_decode($result, true);

$creationdate = new DateTime(date('Y-m-d H:i:s',strtotime($result["created_at"])));
$heute = new DateTime(date('Y-m-d H:i:s'));
$diff = $creationdate->diff($heute);


if($diff->d > 0) {
$f = '%d Tage, %H Stunden, %i Minuten';
} elseif($diff->H > 0) {
$f = '%H Stunden, %i Minuten';
} else {
$f = '%i Minuten';
}

echo $diff->format($f);

Answer

If $result["created_at"] isn't set, strtotime returns the UNIX Epoch (1970-01-01 00:00:00).

It is currently 46 years, 7 months, 12 days, 21 hours, 21 minutes since midnight on 1 January 1970.

This is because the API doesn't return a created_at element at the root of the array, it's in a stream subarray.

This should be obvious if you enable error reporting. You'll get an Undefined index: created_at error message. You can then var_dump($result); to see what's actually returned.

You have a further error: DateInterval doesn't have an H property, it's h.

$url = "https://api.twitch.tv/kraken/streams/" . $_GET['channel'];;

$result = file_get_contents($url);
$result = json_decode($result, true);

$creationdate = new DateTime($result["stream"]["created_at"]);
$heute = new DateTime();
$diff = $creationdate->diff($heute);

if($diff->d > 0) {
    $f = '%d Tage, %H Stunden, %i Minuten';
} elseif($diff->h > 0) {
    $f = '%H Stunden, %i Minuten';
} else {
    $f = '%i Minuten';
}

echo $diff->format($f);
Comments