Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago