Search code examples
phpdatedatediff

Get time between two dates in months only in PHP?


I wrote this script to tell the time in-between two dates

$term_start   = date_create("2018-01-01");
$now          = date_create(date("2019-02-01"));
$diff         = date_diff($term_start,$now);
$amount_spent = $diff->format("%y %m");
echo $amount_spent;

But I want it only in months how do I force it to output 25 instead of 1 1?


Solution

  • If the purpose is to get the months difference between two dates then you may try the following:

    <?php
    $term_start   = date_create("2017-01-01");
    $now          = date_create(date("2019-02-01"));
    $diff         = date_diff($term_start,$now);
    $amount_spent = $diff->format("%y")*12 + $diff->format("%m");
    echo $amount_spent;
    ?>
    

    Output:

    25