All pastes #882064 Raw Edit

Anonymous

public php v1 · immutable
#882064 ·published 2008-01-30 01:20 UTC
rendered paste body
<?phpfunction date_diff ($t1 = null, $t2 = null, $precision = 6, $abbr = false) {    if ($t1 === null)        $t1 = time();    if (preg_match('/\D/', $t1))        $t1 = strtotime($t1);    if ($t2 === null)        $t2 = time();    if (preg_match('/\D/', $t2))        $t2 = strtotime($t2);    // make sure that $t2 > $t1    if ($t1 > $t2)        list($t1, $t2) = array($t2, $t1);    $yrs = 0;    $mnths = 0;    $days = 0;    $hrs = 0;    $mins = 0;    $secs = 0;    // secs    $s2 = (int)date('s', $t2);    while ( ($s1 = (int)date('s', $t1)) !== $s2 ) {        $t1 = strtotime('+1 second', $t1);        $secs++;    }    // mins    $s2 = (int)date('i', $t2);    while ( ($s1 = (int)date('i', $t1)) !== $s2) {        $t1 = strtotime('+1 minute', $t1);        $mins++;    }    // hrs    $s2 = date('G', $t2);    while ( ($s1 = date('G', $t1)) !== $s2 ) {        $t1 = strtotime('+1 hour', $t1);        $hrs++;    }    // days    $s2 = date('j', $t2);    while ( ($s1 = date('j', $t1)) !== $s2 ) {        $t1 = strtotime('+1 day', $t1);        $days++;    }    // mnths    $s2 = date('n', $t2);    while ( ($s1 = date('n', $t1)) !== $s2 ) {        $t1 = strtotime('+1 month', $t1);        $mnths++;    }    // yrs    $s2 = date('Y', $t2);    while ( ($s1 = date('Y', $t1)) < $s2 ) {        $t1 = strtotime('+1 year', $t1);        $yrs++;    }    $stack = array(        array($yrs, ($abbr ? 'yr' : 'year') . ($yrs == 1 ? '' : 's')),        array($mnths, ($abbr ? 'mnth' : 'month') . ($mnths == 1 ? '' : 's')),        array($days, 'day' . ($days == 1 ? '' : 's')),        array($hrs, ($abbr ? 'hr' : 'hour') . ($hrs == 1 ? '' : 's')),        array($mins, ($abbr ? 'min' : 'minute') . ($mins == 1 ? '' : 's')),        array($secs, ($abbr ? 'sec' : 'second') . ($secs == 1 ? '' : 's'))    );    while (count($stack) > 0 && $stack[0][0] == 0)        array_splice($stack, 0, 1);    array_splice($stack, $precision);    $ret = array();    foreach ($stack as $item)        $ret[] = "{$item[0]} {$item[1]}";    return implode(', ', $ret);}echo date_diff('2008-01-29 18:09:06', time(), 3), "\n";?>