2012-07-29 84 views
1

我不知道爲什麼,但返回2小時前所有以下日期以下/時間PHP前段時間函數返回4小時所有日期

function ago($timestamp){ 
     $difference = floor((time() - strtotime($timestamp))/86400); 
     $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade"); 
     $lengths = array("60","60","24","7","4.35","12","10"); 
     for($j = 0; $difference >= $lengths[$j]; $j++) 
      $difference /= $lengths[$j]; 
     $difference = round($difference); 
     if($difference != 1) 
      $periods[$j].= "s"; 
     $text = "$difference $periods[$j] ago"; 
     return $text; 
    } 

我送的日期是

"replydate": "29/07/2012CDT04:54:27", 
"replydate": "29/07/2012CDT00:20:10", 
+0

我認爲你重寫了循環內部的差異。 – 2012-07-29 10:17:19

+0

你是什麼意思? – RussellHarrower 2012-07-29 10:20:34

回答

1

功能strtotime不支持這種格式'29/07/2012CDT00:20:10'。使用這種語法'0000-00-00 00:00:00'。並且不需要86400。所有代碼:

function ago($timestamp){ 
    $difference = time() - strtotime($timestamp); 
    $periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'years', 'decade'); 
    $lengths = array('60', '60', '24', '7', '4.35', '12', '10'); 

    for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j]; 

    $difference = round($difference); 
    if($difference != 1) $periods[$j] .= "s"; 

    return "$difference $periods[$j] ago"; 
} 

echo ago('2012-7-29 17:20:28'); 
+0

這並沒有工作 – RussellHarrower 2012-07-30 01:17:02

1

而不是寫自己的日期/時間函數,你會使用標準的實施,如PHP的DateTime class會更好。正確計算時間有一些微妙之處,比如時區和夏令時。

<?php 
    date_default_timezone_set('Australia/Melbourne'); 

    // Ideally this would use one of the predefined formats like ISO-8601 
    // www.php.net/manual/en/class.datetime.php#datetime.constants.iso8601 
    $replydate_string = "29/07/2012T04:54:27"; 

    // Parse custom date format similar to original question 
    $replydate = DateTime::createFromFormat('d/m/Y\TH:i:s', $replydate_string); 

    // Calculate DateInterval (www.php.net/manual/en/class.dateinterval.php) 
    $diff = $replydate->diff(new DateTime()); 

    printf("About %d hour%s and %d minute%s ago\n", 
     $diff->h, $diff->h == 1 ? '' : 's', 
     $diff->i, $diff->i == 1 ? '' : 's' 
    ); 
?> 
+0

這將工作以及 – RussellHarrower 2012-07-30 10:24:53

相關問題