How to get time difference in minutes in PHP

后端 未结 17 2250
独厮守ぢ
独厮守ぢ 2020-11-21 07:22

How to calculate minute difference between two date-times in PHP?

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 08:01

    The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm. Eg.

    $start_date = new DateTime('2007-09-01 04:10:58');
    $since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
    echo $since_start->days.' days total
    '; echo $since_start->y.' years
    '; echo $since_start->m.' months
    '; echo $since_start->d.' days
    '; echo $since_start->h.' hours
    '; echo $since_start->i.' minutes
    '; echo $since_start->s.' seconds
    ';

    $since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).

    The above code will output:

    1837 days total
    5 years
    0 months
    10 days
    6 hours
    14 minutes
    2 seconds

    To get the total number of minutes:

    $minutes = $since_start->days * 24 * 60;
    $minutes += $since_start->h * 60;
    $minutes += $since_start->i;
    echo $minutes.' minutes';
    

    This will output:

    2645654 minutes

    Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php

提交回复
热议问题