Calculate the number of months between two dates in PHP?

前端 未结 12 1739
无人及你
无人及你 2020-12-01 05:12

Without using PHP 5.3\'s date_diff function (I\'m using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don

12条回答
  •  攒了一身酷
    2020-12-01 06:03

    This is how I ended up solving it. I know I'm a little late but I hope this saves someone a lot time and lines of code.
    I used DateInterval::format to display a human readable countdown clock in years, months, and days. Check https://www.php.net/manual/en/dateinterval.format.php for the format table to see your options on how to modify your return values. Should give you what you're looking for.

    $origin = new DateTime('2020-10-01');
    $target = new DateTime('2020-12-25');
    $interval = $origin->diff($target);
    echo $interval->format('%y years, %m month, %d days until Christmas.');
    

    Outputs: 0 years, 2 month, 24 days

提交回复
热议问题