如果日期已经过去,如何获取年份+1

时间:2019-06-17 11:12:51

标签: php datetime

$mpsAgeT = $today->diff($mpsAgeT);

$today在哪里:

object(DateTime)[37]
  public 'date' => string '2019-06-17 13:40:56.888563' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Sofia' (length=12)

$mpsAgeT是:

object(DateTime)[38]
  public 'date' => string '2016-06-15 13:40:56.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Sofia' (length=12)

还给我3年,但是15.06是较早的日期,所以我想返回4年,已过去3年,开始了4年。

如果我只添加了1年,则如果日期未通过或不相等,它将不起作用。

例如:

17.06.2019 and 17.06.2016 - should returns me 3
17.06.2019 and 19.06.2016 - should returns me 3
17.06.2019 and 15.06.2016 - should returns me 4

2 个答案:

答案 0 :(得分:3)

正如我在评论中所建议的那样,您必须始终添加一个,除非日期完全等于要获得预期的结果:

$diff = $today->diff($mpsAgeT);
$years = $diff->y;

 if (addOne($diff)) {
   $years++;
 }

function addOne($interval) {
    // Iterate precision properties of Interval object
    // In this case, month and days, but can add hours, minutes (check edits)
    // If it's anything other than exact years, should add one
    $props = ['m', 'd'];
    foreach ($props as $prop) {
        // This returns as soon as a property is not 0
        if ($interval->{$prop} !== 0)
          return true;
    }
    return false;
}

Demo

不使用时间间隔的替代解决方案:

// Find year difference
$years = $today->format('Y') - $mpsAgeT->format('Y');
// Add to original date (sets it to the same date of the current year)
// Only add if the date has passed
if ($today > $mpsAgeT->modify('+' . $years . ' years')) {
   $years++;
}

Demo

答案 1 :(得分:1)

您可以简单地检查所有其他变量是否都不为0

$today = new DateTime('2019-06-17 13:40:56.888563');
$mpsAgeT = new DateTime('2016-06-17 13:40:56.888563');
    $interval = $today->diff($mpsAgeT);
    $diff = $interval->format('%y');
    if (!($interval->d === 0 && $interval->m === 0 && $interval->h === 0 && $interval->i === 0 && $interval->s === 0)) {
        $diff++;
    }
    echo $diff; // returns 3

$today = new DateTime('2019-06-17 13:40:56.888563');
$mpsAgeT = new DateTime('2016-06-19 13:40:56.888563');
$interval = $today->diff($mpsAgeT);
$diff = $interval->format('%y');
if (!($interval->d === 0 && $interval->m === 0 && $interval->h === 0 && $interval->i === 0 && $interval->s === 0)) {
    $diff++;
}
echo $diff;// returns 3

$today = new DateTime('2019-06-17 13:40:56.888563');
$mpsAgeT = new DateTime('2016-06-15 13:40:56.888563');
$interval = $today->diff($mpsAgeT);
$diff = $interval->format('%y');
if (!($interval->d === 0 && $interval->m === 0 && $interval->h === 0 && $interval->i === 0 && $interval->s === 0)) {
    $diff++;
}
echo $diff;// returns 4