2013-10-19 98 views
1

我有以下格式時間戳時偏移:2013年10月19日十八時47分30秒如何計算GMT日期戳轉換爲相對時間

我用這來轉換爲相對(x分鐘,幾小時,幾天前)的時間,但它沒有爲最近的用戶返回任何東西,我假設因爲我的系統時間是GMT -3小時,所以它將它解釋爲未來的時間。如果是這樣的話,我怎樣才能在結果中考慮GMT偏移量?

$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':''); 
    } 

} 
+0

'time()'總是返回GMT。無論您的系統時區設置爲何都無關緊要。你不會說你如何獲得你開始的時間戳。他們在格林威治時間嗎 –

+0

嘗試[this](http://stackoverflow.com/a/18602474/67332)函數,它正確地處理時區+它比您的示例更正確地計算差異。 –

回答

0
$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 

$diff變量現在已經因爲$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) 
} 
0

這裏秒,月,日等數是你方法的重寫,這將是更加可靠/精確:

function humanTiming($time){ 
    $timezone=new DateTimeZone("Australia/Melbourne"); // declare whatever your user's timezone is 
    $time=new DateTime($time,$timezone); // input your datetime 
    $now=new DateTime("now",$timezone); // get current datetime 
    if($time>$now){ 
     return "event hasn't happened yet"; 
    }elseif($time==$now){ 
     return "event is happening"; 
    } 
    $diff=(array)$time->diff($now); // get time between now and $time, cast as array 

    $labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second"); 
    $readable="";  // declare as empty string 
    // filter the $diff array to only the desired elements and loop 
    foreach(array_intersect_key($diff,$labels) as $k=>$v){ 
     if($v>0){ // only add non-zero values to $readable 
      $readable.=($readable!=""?", ":"")."$v {$labels[$k]}".($v>1?"s":""); 
      // use comma-space as glue | show value | show unit | pluralize when necessary 
     } 
    } 
    return "event happened $readable ago"; 
} 

echo humanTiming('2013-04-28 17:25:43'); 

// event happened 3 years, 10 months, 23 days, 8 hours, 33 minutes, 59 seconds ago