在yii中显示友好的时间格式

来源:互联网 发布:算法提供者错误 编辑:程序博客网 时间:2024/05/21 17:04

最近在写yii中文百科的程序时遇到了这个问题,本来我一直习惯的是 date("Y-m-d H:i",$time) 的方式。 不过现在很多的网站时间显示为几分钟前几小时前几周前...为了追赶潮流我也写了个方法来实现它。

关于yii里面的格式

yii框架为我们提供了把一些字符串、时间戳等数据格式化为指定格式的类 CFormatter,我使用的方法就是继承了它,然后在配置文件里面修改一下配置就可以直接使用了。

Formatter 代码如下

[php]class Formatter extends CFormatter{    public function formatFriendlyDate($timestamp){        $second = time()-$timestamp;        switch (true){            case $second < 3600:                $m = round($second/60);                if($m == 0 ){                    return "刚刚";                }                return round($second/60).' 分钟前';            case $second < 86400:                return round($second/3600).' 小时前';            case $second < (86400*7):                return round($second/86400).' 天前';            case $second < (86400*7*4):                return round($second/(86400*7)).' 周前';            default :                return $this->formatDatetime($timestamp);        }    }}

配置文件中

[php]...'components' => array(        ...        'format' => array(            'class' => "Formatter",        ),        ...),...

怎么使用?

接下来就是在程序中来使用了,方法如下,

[php]echo Yii::app()->format->formatFriendlyDate($timestamp);

如果你觉得这样使用比较麻烦,你也可以在控制器(Controller)的基类中定义

[php]public function formatDate($timestamp){    return Yii::app()->format->formatFriendlyDate($timestamp);}

在视图(View)中就可以使用比较简单的方法

[php]echo $this->formatDate($timestamp);

以上方法只是说明一下,具体的还是需要根据具体需求来完善。

希望上面的内容对您有用

0 0
原创粉丝点击