一个显示多少时间之前的函数

7 篇文章 0 订阅
4 篇文章 0 订阅
收藏一个老外写的,专门用来显示比如“2 hours ago,1 hour ago"之类时间的函数,
请注意其中对英文单复数时间的处理:
<?php

function Timesince($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , \’year\’),
array(60 * 60 * 24 * 30 , \’month\’),
array(60 * 60 * 24 * 7, \’week\’),
array(60 * 60 * 24 , \’day\’),
array(60 * 60 , \’hour\’),
array(60 , \’min\’),
array(1 , \’sec\’),
);

$today = time(); /* Current unix time */
$since = $today – $original;

// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {

$seconds = $chunks[$i][0];
$name = $chunks[$i][1];

// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
break;
}
}

$print = ($count == 1) ? \’1 \’.$name : \"$count {$name}s\";

if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];

// add second item if its greater than 0
if (($count2 = floor(($since – ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? \’, 1 \’.$name2 : \" $count2 {$name2}s\";
}
}
return $print;
}

?>

  注意传入的是UNIX类型的时间,如果数据库中传入的是TIMESTAMP类型,可以转换下
SELECT id, username, UNIX_TIMESTAMP(joined_data) from UserTable;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值