项目中有个要计算两个时间之间的间隔的需求,但网上一直找不到啥好的方法就自己写了一个,比较粗糙,应该还有很大的优化空间…
/**
* @param $start 起始时间戳
* @param $end 结束时间戳
*/
function timeInterval($start, $end)
{
$return['year'] = 0;//年
$return['mon'] = 0;//月
$return['day'] = 0;//日
$return['hour'] = 0;//时
$return['min'] = 0;//分
$return['sec'] = 0;//秒
do
{
$time = strtotime('+1 year', $start);
if($time <= $end)
{
$return['year'] += 1;
$start = $time;
}
else
{
do
{
$time = strtotime('+1 month', $start);
if($time <= $end)
{
$return['mon'] += 1;
$start = $time;
}
else
{
do
{
$time = $start + 86400;//1天的秒数
if($time <= $end)
{
$return['day'] += 1;
$start = $time;
}
else
{
do
{
$time = $start + 3600;//1小时的秒数
if($time <= $end)
{
$return['hour'] += 1;
$start = $time;
}
else
{
do
{
$time = $start + 60;//1分钟的秒数
if($time <= $end)
{
$return['min'] += 1;
$start = $time;
}
else
{
$return['sec'] = $end - $start;//剩余秒数
}
}while($time < $end);
}
}while($time < $end);
}
}while($time < $end);
}
}while($time < $end);
}
}while($time < $end);
return $return;
}