计算剩余时间的php自定义函数一例

发布时间:2019-10-10编辑:脚本学堂
分享一个计算剩余时间的php自定义函数,很简单,把两个日期格式的字符串转化成unix时间戳,然后相减获得时间戳差。有需要的朋友参考下。

本节内容:
计算剩余时间的php自定义函数

思路:
把两个日期格式的字符串转化成unix时间戳,然后相减获得时间戳差。
最后判断剩余时间,生成类似(2小时30分钟20秒前发布)这样的时间格式。

例子:
 

复制代码 代码示例:

<?php
/**
* 计算剩余时间
* by www.jb200.com
*/

public function gettime($time_s,$time_n){
$time_s = strtotime($time_s);
$time_n = strtotime($time_n);
$strtime = '';
$time = $time_n-$time_s;
if($time >= 86400){
return $strtime = date('Y-m-d H:i:s',$time_s);
}
if($time >= 3600){
$strtime .= intval($time/3600).'小时';
$time = $time % 3600;
}else{
$strtime .= '';
}
if($time >= 60){
$strtime .= intval($time/60).'分钟';
$time = $time % 60;
}else{
$strtime .= '';
}
if($time > 0){
$strtime .= intval($time).'秒前';
}else{
$strtime = "时间错误";
}
return $strtime;
}