简体   繁体   中英

PHP - How to subtract an older date from a newer date?

如何使用PHP从较新的日期中减去较旧的日期2010-10-18 07:44:53

I would advise working with timestamps. subtract one from the other, the difference is seconds, then simple logic to convert it to mins/hours/days ect.

you can use date , strtotime , mktime to get a timestamp

date_diff

http://php.net/manual/en/function.date-diff.php

If you are using DateTime objects the method is diff

Answering the question kind of depends on what return value you want. Seconds? Minutes? Here's a simple function you can try to get the value in any form you want:

<?php
define('SUBDATES_SECS', 0);
define('SUBDATES_MINS', 1);
define('SUBDATES_HOURS', 2);
define('SUBDATES_DAYS', 3);
define('SUBDATES_WEEKS', 4);
define('SUBDATES_MONTHS', 5);
define('SUBDATES_YEARS', 6);
function sub_dates($older, $newer, $ret = SUBDATES_SECS) {
    $older = (is_numeric($older)) ? $older : strtotime($older);
    $newer = (is_numeric($newer)) ? $newer : strtotime($newer);

    $result = $newer - $older;
    switch($ret) {
        case SUBDATES_MINS:
            $result /= 60;
            break;
        case SUBDATES_HOURS:
            $result /= 120;
            break;
        case SUBDATES_DAYS:
            $result /= 86400;
            break;
        case SUBDATES_WEEKS:
            $result /= 604800 ;
            break;
        case SUBDATES_MONTHS:
            $result /= 2629743;
            break;
        case SUBDATES_YEARS:
            $result /= 31556926;
            break;
    }

    return $result;
}

Using it:

<?php
$older = time();
sleep(3);
$newer = time();
echo sub_dates($older, $newer);
// Returns 3

echo sub_dates($older, $newer, SUBDATES_MINS);
// Returns 0.05

echo sub_dates('2010-04-19 01:01:00', '2010-04-19 01:02:00', SUBDATES_MINS);
// Returns 1

It's pretty untested though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM