php实现用已经过去多长时间的方式显示时间

yipeiwu_com5年前PHP代码库

本文实例讲述了php用已经过去多长时间的方式显示时间的方法。分享给大家供大家参考。具体如下:

这里以一种可读性比较好的方式显示已经过去多长时间,比如:距离现在10秒,距离现在1天等等。

function time_is_older_than($t, $check_time){
  $t = strtolower($t);
  $time_type = substr(preg_replace('/[^a-z]/', '', $t), 0, 1);
  $val = intval(preg_replace('/[^0-9]/', '', $t));
  $ts = 0;
  // (s)econds, (m)inutes, (d)ays, (y)ears
  if ($time_type == 's'){ $ts = $val; }
  else if ($time_type == 'm'){ $ts = $val * 60; }
  else if ($time_type == 'h'){ $ts = $val * 60 * 60; }
  else if ($time_type == 'd'){ $ts = $val * 60 * 60 * 24; }
  else if ($time_type == 'y'){ $ts = $val * 60 * 60 * 24 * 365; }
  else { die('Unknown time format given!'); }
  if ($check_time < (time()-$ts)){ return true; }
  return false;
}

//使用范例:
// timestamp to test: 
// (could be from an database or something else)
$time = 1146722922;
// long if check:
if (time_is_older_than('30m', $time)){
  print 'The given timestamp: ' . date('l dS \of F Y h:i:s A',$time);
  print " - is older than 30 minutes<br/>\n";
}
else {
  print 'The given timestamp: ' . date('l dS \of F Y h:i:s A',$time);
  print " - is NOT older than 30 minutes<br/>\n";
}
// short checks:
if (time_is_older_than('10s', $time)){ print "Is older than 10 seconds<br/>\n"; }
if (time_is_older_than('200m', $time)){ print "Is older than 200 minutes<br/>\n"; }
if (time_is_older_than('2h', $time)){ print "Is older than 2 hours<br/>\n"; }
if (time_is_older_than('4d', $time)){ print "Is older than 4 days<br/>\n"; }
if (time_is_older_than('1y', $time)){ print "Is older than one year<br/>\n"; }

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

相关文章

5种PHP创建数组的实例代码分享

看这篇文章之前相信大家都已经看过PHP中文手册关于数组这一节的讲解了,怎么样呢,看懂了多少?至少我第一次阅读文档时是一头雾水,也许是因为在翻译的不够通俗易懂吧^_^!!这里UncleTo...

PHPwind整合最土系统用户同步登录实现方法

上次成功升级了最土商业版,接下来就是整合公司的社区网站,先说明一下我现在工作的地方是个地方社区网站,用的基础程序是PHPWind,我的任务就是让PHPWind和最土登录同步,领导也知道我...

php的一个登录的类 [推荐]

PHP代码: <? /* * 名称:CnkknD PHP Login Class * 描述:PHP用于登录的类,基于MySQL *...

Laravel 5.3 学习笔记之 错误&日志

1、简介 Laravel默认已经为我们配置好了错误和异常处理,我们在App\Exceptions\Handler类中触发异常并将响应返回给用户。本教程我们将深入探讨这个类。 此外,La...

漂亮的thinkphp 跳转页封装示例

漂亮的thinkphp 跳转页封装示例

项目是要一点点按优先级进行优化的,现在到优化thinkphp的跳转页了。<?php  if(C('LAYOUT_ON')) {  &...