Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Berechnet die Differenz zwischen zwei Daten in PHP

Sie könnten die Funktion date_diff() verwenden

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

So etwas wie...

<?php 
$now = time();
$then = $posttime;
$diff = date_diff($now,$then);
echo $diff->format('%R%d days'); #change format for different timescales
?>

bearbeiten --

Ich löse dieses Problem tatsächlich in einer meiner Twitter-Apps mit dieser Funktion ...

function time_since ( $start )
{
    $end = time();
    $diff = $end - $start;
    $days = floor ( $diff/86400 ); //calculate the days
    $diff = $diff - ($days*86400); // subtract the days
    $hours = floor ( $diff/3600 ); // calculate the hours
    $diff = $diff - ($hours*3600); // subtract the hours
    $mins = floor ( $diff/60 ); // calculate the minutes
    $diff = $diff - ($mins*60); // subtract the mins
    $secs = $diff; // what's left is the seconds;
    if ($secs!=0) 
    {
        $secs .= " seconds";
        if ($secs=="1 seconds") $secs = "1 second"; 
    }
    else $secs = '';
    if ($mins!=0) 
    {
        $mins .= " mins ";
        if ($mins=="1 mins ") $mins = "1 min "; 
        $secs = '';
    }
    else $mins = '';
    if ($hours!=0) 
    {
        $hours .= " hours ";
        if ($hours=="1 hours ") $hours = "1 hour ";             
        $secs = '';
    }
    else $hours = '';
    if ($days!=0) 
    {
        $days .= " days "; 
        if ($days=="1 days ") $days = "1 day ";                 
        $mins = '';
        $secs = '';
        if ($days == "-1 days ") {
            $days = $hours = $mins = '';
            $secs = "less than 10 seconds";
        }
    }
    else $days = '';
    return "$days $hours $mins $secs ago";
}

Sie übergeben es in einem Unix-Zeitstempel der zu prüfenden Zeit (die Postzeit) und es gibt die verschiedenen Zeichenfolgen zurück.