如果你使用MySQL的日期格式你可以一步借此,并计算年,月,日,小时,等...例如,像这样的功能可能工作:
function get_time_diff($start_date, $end_date = null) {
// make sure start date is in mysql datetime format
$expr = "/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s([0-1][0-9]|2[0-3])(:[0-5][0-9]){2}?$/";
if (!preg_match($expr, $start_date)) {
return false;
}
if (isset($end_date)) {
// make sure end date is in mysql datetime format
if(!preg_match($expr, $end_date)) {
return false;
}
list($date, $time) = explode(' ', $end_date);
list($hour, $minute, $second) = explode(':', $time);
$today = new DateTime($date);
$today->setTime($hour, $minute, $second);
} else {
$today = new DateTime();
}
$target = new DateTime($start_date);
$diff = $today->diff($target);
if ($diff->y > 0) {
echo $diff->y . ' year' . ($diff->y > 1 ? 's' : '') . ($diff->m > 0 ? ', ' : '');
}
if ($diff->m > 0) {
echo $diff->m . ' month' . ($diff->m > 1 ? 's' : '') . ($diff->d > 0 ? ', ' : '');
}
if ($diff->d > 0) {
echo $diff->d . ' day' . ($diff->d > 1 ? 's' : '') . ($diff->h > 0 ? ', ' : '');
}
if ($diff->h > 0) {
echo $diff->h . ' hour' . ($diff->h > 1 ? 's' : '') . ($diff->i > 0 ? ', ' : '');
}
if ($diff->i > 0) {
echo $diff->i . ' minute' . ($diff->i > 1 ? 's' : '') . ($diff->s > 0 ? ', ' : '');
}
if ($diff->s > 0) {
echo $diff->s . ' second' . ($diff->s > 1 ? 's' : '');
}
return $today < $target ? ' until' : ' ago';
}
if ($test = get_time_diff('2012-09-11 10:25:00')) {
echo $test;
} else {
echo 'invalid request';
}
这将输出类似:1年7个月,14天5个小时58分6秒前
你真的不应该使用的strtotime()或UNIX由于其时间戳日期范围有限。
感谢您的帮助,我已经找到了解决方案。当函数进行计算时,我已将时间戳放在$ currentdate和$ timefromdb之前。 –