我在stackoverflow URL
中读到了一篇关于时差的文章$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
这是一个计算时差的代码,如你所知,我需要一个时间差异插入到db中,但如果时间差小于0年它也会插入0年,我该如何防止这种情况? / p>
答案 0 :(得分:0)
只需使用y
循环m
,d
,foreach
值,如果它们在每种情况下总计超过0,则添加它们吗?
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
$description = [];
foreach (["year", "month", "day"] as $unit) {
$value = $difference->{substr($unit, 0, 1)};
switch ($value) {
case 0: break;
case 1: $description[] = "1 $unit"; break;
default: $description[] = "$value {$unit}s"; break;
}
}
echo "Difference: " . implode(", ", $description);