PHP 时间戳直到“小时前"麻烦 [英] PHP Timestamp until "hours ago" trouble

查看:30
本文介绍了PHP 时间戳直到“小时前"麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定我们网站中已发布评论的时间前"时间戳.我的老板希望它只显示到几个小时.所以它应该显示48 小时前"而不是2 天前"或 480 小时而不是20 天前".

I need to determine the "time ago" timestamp of the posted comment/s in our site. my boss wants it to display until hours only. so it should display "48 hours ago" instead of "2days ago" or 480hours instead of "20days ago".

这是我找到的代码,但直到几个小时我才知道该怎么做.

here's the code that I found but I don't know how to do it until hours only.

 date_default_timezone_set('Asia/Taipei');
 class Cokidoo_DateTime extends DateTime {

    protected $strings = array(
        'y' => array('1 year ago', '%d years ago'),
        'm' => array('1 month ago', '%d months ago'),
        'd' => array('1 day ago', '%d days ago'),
        'h' => array('1 hour ago', '%d hours ago'),
        'i' => array('1 minute ago', '%d minutes ago'),
        's' => array('now', '%d secons ago'),
    );

    /**
     * Returns the difference from the current time in the format X time ago
     * @return string
     */
    public function __toString() {
        $now = new DateTime('now');
        $diff = $this->diff($now);

        foreach($this->strings as $key => $value){
            if( ($text = $this->getDiffText($key, $diff)) ){
                return $text;
            }
        }
        return '';
     }

    /**
     * Try to construct the time diff text with the specified interval key
     * @param string $intervalKey A value of: [y,m,d,h,i,s]
     * @param DateInterval $diff
     * @return string|null
     */
     protected function getDiffText($intervalKey, $diff){
        $pluralKey = 1;
        $value = $diff->$intervalKey;
        if($value > 0){
        if($value < 2){
            $pluralKey = 0;
            }
            return sprintf($this->strings[$intervalKey][$pluralKey], $value);
        }
        return null;
    }
 }
echo $date = new Cokidoo_Datetime('2012-11-28 0:59:44');

推荐答案

工作示例:您的类修改为仅返回小时差异.

Working example : Your class modified to return difference in hours only.

<?php
class Cokidoo_DateTime extends DateTime {
    public function __toString() {
        $now = new DateTime('now');
        $diff = $this->diff($now);        
        return $this->getHours($diff);
     }

     function getHours($diff) {
        $hours =  ($diff->d * 24) + $diff->h; 
        return (string)$hours;
     }
 }
echo $date = new Cokidoo_Datetime('2012-11-28 0:59:44');
?>

这篇关于PHP 时间戳直到“小时前"麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆