Development

Convert Unix time to now in PHP

A Unix timestamp looks like 1514452438 if you wanted to output how long ago this was such as 4 days, 18 hours, 44 minutes and 15 seconds in PHP here is a handy function

function timeDiff($timestamp)
{
    $how_long_ago = '';
    $seconds = time() - $timestamp;
    $minutes = (int)($seconds / 60);
    $hours = (int)($minutes / 60);
    $days = (int)($hours / 24);
    if ($days >= 1) {
        $how_long_ago = $days . ' day' . ($days != 1 ? 's' : '');
    } else if ($hours >= 1) {
        $how_long_ago = $hours . ' hour' . ($hours != 1 ? 's' : '');
    } else if ($minutes >= 1) {
        $how_log_ago = $minutes . ' minute' . ($minutes != 1 ? 's' : '');
    } else {
        $how_long_ago = $seconds . ' second' . ($seconds != 1 ? 's' : '');
    }
    return $how_long_ago;
}

simple call the function with your Unix timestamp to be converted like:

echo timeDiff(1514452438);

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago