2019-03-15 Pujan Niroula 1 Minute(s) Read

[How to] Create Time Ago in PHP

img-php time ago function thumbnail.jpg

 Hello there,
After a long time I am back with simple and little tricky but widely used code. If you want to create time ago system just like facebook. This is just a simple and tiny function which will convert PHP timestamp.

If you stored time with time() function in then this will be very easy just use the following function. Time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

function get_time($t_time) {
    $pt = time() - $t_time;
    if ($pt>31536000)
        $p = date("Y-M-j",$t_time);
    elseif ($pt>=86400)
        $p = date("M-j",$t_time);
    elseif ($pt>=3600)
        $p = (floor($pt/3600))."h ago";
    elseif ($pt>=60)
        $p = (floor($pt/60))."m ago";
    elseif ($pt<2)
        $p="Just now";
        $p = $pt."s ago";
    return $p;

If current time is greater than an year(31536000 seconds) then this will return full date  yy-mm-dd similarly if current time is less than an year  this will return just  mm-dd format furthermore it will return  hour, minute and second ago.

To call the function just type get_time(time()-100);

Thanks for reading :)

Tags:php, how to, time,
Comments (2) Add New Comment
sklep online2024-02-22 7:28 AM

Wow, wonderful weblog format! How long have you been running a blog for? you make blogging glance easy. The whole look of your web site is wonderful, let alone the content material! You can see similar: e-commerce and here najlepszy sklep

Yoho Cloud2023-05-09 7:10 AM

It help us alots and thanks for sharing such master piece .