我花了一些时间做这个快速的小函数(我没有使用默认函数,因为我想稍后进行更多的自定义)。我做了一个有$checkTime = '0';
的帖子,当运行这个函数时,它返回为49 years ago
。
为什么回到1970年1月只有45年前?额外的 4 年来自时差和闰年吗?
其他时间似乎工作正常(最近的时间),但我设置为 0 的那些说了出来,我只是好奇错误在哪里,或者我可能忽略了什么。
function relativeTime($string) {
$currentTime = time();
$checkTime = $string;
$timeDifference = $currentTime - $checkTime;
if($timeDifference > '0') {
$timeSeconds = round(($timeDifference / 60) * 60);
$timeMinutes = round($timeSeconds / 60);
$timeHours = round($timeMinutes / 60);
$timeDays = round($timeHours / 24);
$timeWeeks = round($timeDays / 7);
$timeMonths = round($timeWeeks / 4);
$timeYears = round($timeMonths / 12);
if($timeSeconds < '2') {
return ''.$timeSeconds.' second ago';
} elseif($timeSeconds < '60') {
return ''.$timeSeconds.' seconds ago';
} elseif($timeMinutes < '2') {
return ''.$timeMinutes.' minute ago';
} elseif($timeMinutes < '60') {
return ''.$timeMinutes.' minutes ago';
} elseif($timeHours < '2') {
return ''.$timeHours.' hour ago';
} elseif($timeHours < '24') {
return ''.$timeHours.' hours ago';
} elseif($timeDays < '2') {
return ''.$timeDays.' day ago';
} elseif($timeDays < '7') {
return ''.$timeDays.' days ago';
} elseif($timeWeeks < '2') {
return ''.$timeWeeks.' week ago';
} elseif($timeWeeks < '4') {
return ''.$timeWeeks.' weeks ago';
} elseif($timeMonths < '2') {
return ''.$timeMonths.' month ago';
} elseif($timeMonths < '12') {
return ''.$timeMonths.' months ago';
} elseif($timeYears < '2') {
return ''.$timeYears.' year ago';
} elseif($timeYears > '1') {
return ''.$timeYears.' years ago';
} else {
return $timeSeconds;
}
} else {
return 'The Future';
}
}
因为你的计算搞砸了。查看一个示例并检查所有公式
<?
//same numbers, different formula
$checkTime=0;
echo (time()-$checkTime)/31536000; //45.094949422882 Years
?>
31536000
是 1 年中的秒数。
即使使用它,您也必须注意闰年。我们不能将时间戳除以分钟,然后除以小时,然后除以天,依此类推。如果您需要准确的结果,则输入也必须准确。
还记得美国常用的著名的双周和每月两次付款吗?从远处看,它们似乎意味着同样的事情,但事实并非如此。因此,像你的代码一样划分会失去所有的准确性,当这种差异乘以 45 年时,它变得很大。
小提琴