php计算给定时间之前的函数用法实例

yipeiwu_com6年前PHP代码库

本文实例讲述了php计算给定时间之前的函数用法。分享给大家供大家参考。具体如下:

这里给定一个时间,计算这个时间在多久前,比如:2天前,1年前

<?php
function prettyDate($date){
  $time = strtotime($date);
  $now = time();
  $ago = $now - $time;
  if($ago < 60){
    $when = round($ago);
    $s = ($when == 1)?"second":"seconds";
    return "$when $s ago";
  }elseif($ago < 3600){
    $when = round($ago / 60);
    $m = ($when == 1)?"minute":"minutes";
    return "$when $m ago";
  }elseif($ago >= 3600 && $ago < 86400){
    $when = round($ago / 60 / 60);
    $h = ($when == 1)?"hour":"hours";
    return "$when $h ago";
  }elseif($ago >= 86400 && $ago < 2629743.83){
    $when = round($ago / 60 / 60 / 24);
    $d = ($when == 1)?"day":"days";
    return "$when $d ago";
  }elseif($ago >= 2629743.83 && $ago < 31556926){
    $when = round($ago / 60 / 60 / 24 / 30.4375);
    $m = ($when == 1)?"month":"months";
    return "$when $m ago";
  }else{
    $when = round($ago / 60 / 60 / 24 / 365);
    $y = ($when == 1)?"year":"years";
    return "$when $y ago";
  }
}
echo prettyDate("2012-07-22 12:23:45")."<br />";
echo prettyDate("2010-11-12 22:25:45")."<br />";
echo prettyDate("2012-01-01 01:00:00")."<br />";
echo prettyDate("2001-05-30 00:00:00")."<br />";

希望本文所述对大家的php程序设计有所帮助。

相关文章

php Try Catch异常测试

页面try catch里使用c的 c1,c1里使用b的b1,b1里使用a的a1。 默认的是:a1里抛出异常,b1里捕获a1的异常,然后再把刚才的异常抛出,c1捕获,然后抛出,最后页面捕获...

PHP简单读取PDF页数的实现方法

本文实例讲述了PHP简单读取PDF页数的实现方法。分享给大家供大家参考,具体如下: 还是老外比较厚道, 在老外的网站找到了这样一个方法, 我写成了一个函数, 再将函数写进自己的LeeLi...

PHP获取指定函数定义在哪个文件中以及其所在的行号实例

当调试开源的代码时,希望查看某个函数的定义,那么就需要定位其位置。在 zend studio 这样的 IDE 中自是可以自动提示到,但当没有安装这样的开发工具时,我们可以怎么办呢?参考如...

php采集文章中的图片获取替换到本地(实现代码)

复制代码 代码如下:/** * 获取替换文章中的图片路径 * @param string $xstr 内容 * @param string $keyword...

phpwind中的数据库操作类

<?php /*来源:phpwind.net*/ Class DB { var $query_num = 0; function&...