Page 1 of 1

PHP Help with time since x happened

Posted: Tue Nov 01, 2016 7:02 am
by smashapps
Hey guys,

Been awhile I know, but I am working on a new project. It is a ticketing system.
One of the features on the site is a chat box, you can enter a message and click send and the message will show up with your name however I want to know if anyone knows of a function i can put in to be able to show for example "Posted 5 minutes ago" or "Posted 1 week, 2 days ago" in the chat.

I know there are a few examples hanging around online but I've had trouble getting them to work.

The way I generate the time in my mysql database is with this:
Code: Select all
$timeadded = date("h:ia");
that's hours:minutes am/pm

Image

Any help would be greatly appreciated :)

Re: PHP Help with time since x happened

Posted: Tue Nov 01, 2016 2:52 pm
by CodenStuff
Are you actually saving the time to the database as "3:45am" or is it stored as a timestamp and you're outputting it as "3:45am"?

Re: PHP Help with time since x happened

Posted: Tue Nov 01, 2016 4:09 pm
by Filip
smashapps wrote:
Code: Select all
$timeadded = date("h:ia");
So you only store time in database? Not date as well?

Re: PHP Help with time since x happened

Posted: Wed Nov 02, 2016 1:46 am
by smashapps
Now I feel like an idiot, lol.

Forget the code I posted. I was using timestamp in the database which is the date/time

Re: PHP Help with time since x happened

Posted: Wed Nov 02, 2016 3:47 pm
by CodenStuff
Would this help?
Code: Select all
<?php
function time_elapsed($secs){
    $bit = array(
        ' year'        => $secs / 31556926 % 12,
        ' week'        => $secs / 604800 % 52,
        ' day'        => $secs / 86400 % 7,
        ' hour'        => $secs / 3600 % 24,
        ' min'    => $secs / 60 % 60,
        ' sec'    => $secs % 60
        );
        
    foreach($bit as $k => $v){
        if($v > 1)$ret[] = $v . $k . 's';
        if($v == 1)$ret[] = $v . $k;
        }
    array_splice($ret, count($ret)-1, 0, 'and');
    $ret[] = 'ago.';
    
    return join(' ', $ret);
    }

//This would be your time from database
$time_from_db = 1478101347;

echo 'Posted ' . time_elapsed(time()-$time_from_db);
?>
Lots of time function examples here that should help you achieve your goal:
http://php.net/manual/en/function.time.php#89415

Re: PHP Help with time since x happened

Posted: Wed Nov 02, 2016 4:13 pm
by smashapps
I changed the way my time is stored in the database and used the function you posted and it is all working great now!

Thanks heaps for that, I think I tried a function similar the other day but I was using the incorrect timestamp. Simple things get so easily overlooked.

:)