【问题标题】:PHP time ago function returning 4 hours for all datesPHP时间前函数返回所有日期的4小时
【发布时间】:2012-07-29 10:12:08
【问题描述】:

我不知道为什么,但是以下所有日期/时间在 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",   

【问题讨论】:

  • 我认为您正在覆盖循环内部的差异。

标签: php date timestamp timeago


【解决方案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');

【讨论】:

    【解决方案2】:

    与其编写自己的日期/时间函数,不如使用像 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'
        );
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多