为了显示一个事件的持续时间,我试图计算两个日期之间的差异。如果事件的持续时间为星期五17:00至星期日15:00,则针对该问题给出的大多数函数都将失败。我的目标是找出日期之间的区别,比如:
date('Ymd',$end)-date('Tmd',$begining);
但这很可能会失败,因为一年没有99个月,一个月没有99天。我可以将日期字符串转换为unix时间戳,然后除以60*60*12,但有些日子的小时数要么大要么小,有时会有一个闰秒。所以我使用getDate()创建了自己的函数,它返回一个关于时间戳的innformation数组。
/*
* datediff($first,$last)
* $first - unix timestamp or string aksepted by strtotime()
* $last - unix timestamp or string aksepted by strtotime()
*
* return - the difference in days betveen the two dates
*/
function datediff($first,$last){
$first = is_numeric($first) ? $first : strtotime($first);
$last = is_numeric($last ) ? $last : strtotime($last );
if ($last
// Can't calculate negative difference in dates
return -1;
}
$first = getdate($first);
$last = getdate($last );
// find the difference in days since the start of the year
$datediff = $last['yday'] - $first['yday'];
// if the years do not match add the appropriate number of days.
$yearCountedFrom = $first['year'];
while($last['year'] != $yearCountedFrom ){
// Take leap years into account
if( $yearCountedFrom % 4 == 0 && $yearCountedFrom != 1900 && $yearCountedFrom != 2100 ){
//leap year
$datediff += 366;
}else{
$datediff += 365;
}
$yearCountedFrom++;
}
return $datediff;
}
关于gregoriantojd()函数,它可能会工作,但是我有点不安,因为我不理解它是如何工作的。