简体   繁体   中英

PHP: Count the past hours / days

I've a timestamp in this format here: 2019-05-21 19:57:21 Now I want to display the hours / days that are past from this timestamp.

For example when the timestamp is older than 2 minutes, I want to print 2 minutes until it reached 59 minutes .

From know on it must be hours. So for example after 59 hours it should be 1 hour .

After reaching 24 hours , it should say 1 day , 2 days . After one week, it should print 1 week (we'll let the years out).

This is what I've done by myself. I'm don't know how I can complete this:

$timestamp = '2019-05-21 19:57:21';

function calculate_notification_time( $notification_time ) {

    $now  = new DateTime( date( 'Y-m-d H:i:s' ) );
    $past = new DateTime( $notification_time );
    $dt   = $now->diff( $past );

    error_log( print_r( $now, true ) );

    if ( $dt->y > 0 ) {
        $number = $dt->y;
        $unit   = 'Jahr';
    } else if ( $dt->m > 0 ) {
        $number = $dt->m;
        $unit   = 'Monat';
    } else if ( $dt->d > 0 ) {
        $number = $dt->d;
        $unit   = 'Tag';
    } else if ( $dt->h > 0 ) {
        $number = $dt->h;
        $unit   = 'Stunde';
    } else if ( $dt->i > 0 ) {
        $number = $dt->i;
        $unit   = 'Minute';
    } else if ( $dt->s > 0 ) {
        $number = $dt->s;
        $unit   = 'einigen Sekunden';
    }

    if ( ! empty( $unit ) && ! empty( $number ) && $number > 1 ) {

        switch ( $unit ) {
            case 'Jahr':
                $unit .= 'en';
                break;
            case 'Monat':
                $unit .= 'en';
                break;
            case 'Tag':
                $unit .= 'en';
                break;
            case 'Stunde':
                $unit .= 'n';
                break;
            case 'Minute':
                $unit .= 'n';
                break;
            default:
                break;
        }

        return $number . ' ' . $unit;
    }

    return 'Zeit nicht Verfügbar';
}

UPDATE:

With the help of an answer I've figured this out. The strange thing is that the minutes are totally wrong and going backwards. So 20 minutes ago it was 35 minutes and now its 15 minutes. So strange....

$timestamp = '2019-05-21 11:49:21';
$unixTimestampS = strtotime($timestamp);
$dNow =  strtotime("now");
$diff = $dNow- $unixTimestampS;
if($diff <60) {
    $result =  $diff. ' seconds ago'; // When it's not 1 minute
} elseif (($dNow- $unixTimestampS) > 60 && ($dNow- $unixTimestampS) < 3600) {
    $result = $diff . ' minute ago'; // For example: 19 minutes
}
echo $result;

or a better approach is mentioned here How to get time difference in minutes in PHP

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