2012-07-29 90 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