如何使用 PHP 创建人类可读的日期差异字符串?
示例:
date_diff
似乎不支持这一点,至少不支持所需的细节。
答案 0 :(得分:1)
此函数采用两个时间戳并将其转换为可读的格式。
<强>示例:强>
public static function FormatTimeSpan($time1, $time2)
{
$diff = date_diff(new DateTime(date('Y-m-d H:i:s', $time1)), new DateTime(date('Y-m-d H:i:s', $time2)));
$items = [ ];
if ($diff->y > 0) $items[] = $diff->y == 1 ? '1 year' : $diff->y . ' years';
if ($diff->m > 0) $items[] = $diff->m == 1 ? '1 month' : $diff->m . ' months';
if ($diff->d > 0) $items[] = $diff->d == 1 ? '1 day' : $diff->d . ' days';
if (count($items) == 0) $items[] = '0 days';
$last = array_pop($items);
return count($items) == 0 ? $last : implode(', ', $items) . ' and ' . $last;
}
答案 1 :(得分:0)
我不久前做了一个功能。
/**
* Calculate the time between two dates
* If the second date is not specified it takes the current day
* @author rsalcedo
* @param date ("Y-m-d") (aaaa-mm-dd) $from
* @param date ("Y-m-d") (aaaa-mm-dd) $to
*/
function years_months_days($from,$to="") {
try {
$myFrom = new DateTime($from);
$myAcarreo = 0;
if ($to=="" || null)
$to=date("Y-m-d");
$myTo = new DateTime($to);
$diff_year = $myTo->format("Y") - $myFrom->format("Y") ;
$diff_mnth = $myTo->format("m") - $myFrom->format("m") ;
$diff_days = $myTo->format("d") - $myFrom->format("d") ;
if ($diff_days<0){
$diff_days = $diff_days + 30;
$myAcarreo = -1;
}
$diff_mnth = $diff_mnth + $myAcarreo;
$myAcarreo = 0;
if ($diff_mnth<0){
$diff_mnth = $diff_mnth + 12;
$myAcarreo = -1;
}
$diff_year = $diff_year + $myAcarreo;
return array($diff_year,$diff_mnth,$diff_days);
} catch (Exception $e) {
echo $e;
}
}
您可以这样使用:
list($edad,$edadMes,$edadDias) = years_months_days("1979-09-12");
echo "$edad years, $edadMes months, $edadDias days.";
list($edad,$edadMes,$edadDias) = years_months_days("1979-09-12","2008-07-18");
echo "$edad years, $edadMes months, $edadDias days.";
欢迎改进!
答案 2 :(得分:0)
尝试一下,这已经过测试。
$date1 = date_create("2017-11-27");
$date2 = date_create("2018-12-29");
$diff=date_diff($date1,$date2);
$months = $diff->format("%m months");
$years = $diff->format("%y years");
$days = $diff->format("%d days");
echo $years .' '.$months.' '.$days;
输出为:
1 years 1 months 2 days