防止将0年插入db - 时间差

时间:2016-06-26 15:47:56

标签: php html time difference

我在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>

1 个答案:

答案 0 :(得分:0)

只需使用y循环mdforeach值,如果它们在每种情况下总计超过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);