doudou8783 2013-10-19 21:36
浏览 145

如何在将日期时间戳转换为相对时间时考虑GMT偏移

I have timestamps in the following format: 2013-10-19 18:47:30

I am using this to convert to relative (x minutes, hours, days ago) time but it returns nothing for the most recent users, I assume because my system time is GMT -3 hours so it is interpreting it as a time in the future. If that is the case, how can I take the users GMT offset into account in the result?

$time = strtotime('2013-04-28 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

function humanTiming ($time)
{

    $time = time() - $time; // to get the time since that moment

    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }

}
  • 写回答

2条回答 默认 最新

  • ds355020 2013-12-17 14:04
    关注
    $eventTimeString = '2013-04-28 17:25:43';
    $timezone = new DateTimeZone("Etc/GMT+3"); // Same as GMT-3, here you should use the users's timezone
    $eventTime = new DateTime($eventTimeString , $timezone);
    
    $diff = $eventTime->diff(new DateTime()); // Compare with 
    

    The $diff variable now has number of seconds, months, days etc. since $eventTime

    object(DateInterval)#4 (15) {
      ["y"]=>
      int(0)
      ["m"]=>
      int(7)
      ["d"]=>
      int(18)
      ["h"]=>
      int(17)
      ["i"]=>
      int(35)
      ["s"]=>
      int(38)
      ["weekday"]=>
      int(0)
      ["weekday_behavior"]=>
      int(0)
      ["first_last_day_of"]=>
      int(0)
      ["invert"]=>
      int(0)
      ["days"]=>
      int(232)
      ["special_type"]=>
      int(0)
      ["special_amount"]=>
      int(0)
      ["have_weekday_relative"]=>
      int(0)
      ["have_special_relative"]=>
      int(0)
    }
    
    评论

报告相同问题?