dpdhsq0783 2016-08-13 20:20
浏览 49
已采纳

查询Twitch API时DateTime :: diff返回的意外值

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);
  • 写回答

1条回答 默认 最新

  • duanqiao1949 2016-08-13 21:54
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度