PHP Time Between Dates

Is there an efficient way to get the time period between two dates?

For example:
Date 1: 2015-11-14
Date 2: 2017-2-19
Should result in 1 year, 3 months, 5 days.

A small library maybe?

Comments 3

  • I can suggest the Carbon PHP library for this. It has a handy method - diffForHumans that can output something similar. Here is how it's used:

    <?php
    
    use Carbon\Carbon;
    
    $firstDate = Carbon::parse('2017-02-19');
    $secondDate = Carbon::parse('2015-11-14');
    
    echo $firstDate->diffForHumans($secondDate);
    

    A thing to keep in mind is that by default this rounds up to the larger unit, so the library would only output "1 Year", instead of 1 Year, X months.

  • I have also used Carbon many times. It makes life easier, because Date has always been a painful thing in php.