Simple time ago sollution for real time message system?

I am looking for a very simple time ago sollution for a real time message system. So instead of displaying the timestamp from the database, I would like to display the time ago it was posted in minutes, hours or days

This is what I have so far:

// Model

public function get_messages()
{
    $sql    =    "SELECT M.message
                      , M.sended
                      , U.username
                   FROM messages M
                   JOIN users U ON M.user_id = U.id";
                  
        $stmt    = $this->pdo->query($sql);
        
        return $stmt->fetchAll();
}

// Controller

public function pollMessagesAction()
{
    $message_list = $this->messages->get_messages();
            
    if ($message_list) {
            
        $messages_html  = new View('/users/partials/message_list.php', compact('message_list'));
                        
        $output = array(
            'messages'          => $messages_html->render()
        );
        header('Content-Type: application/json');
        echo json_encode($output, JSON_FORCE_OBJECT);    
    }
    exit();        
}

EDIT: I found the following function:

    public function get_timeago( $ptime )
    {
        $estimate_time = time() - $ptime;

        if( $estimate_time < 1 )
        {
            return 'less than 1 second ago';
        }

        $condition = array( 
                12 * 30 * 24 * 60 * 60  =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
        );

        foreach( $condition as $secs => $str )
        {
            $d = $estimate_time / $secs;

            if( $d >= 1 )
            {
                $r = round( $d );
                return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
            }
        }
    }

But I have no ideahow to return the value of this function to the get_mesages() function. All help would be highly appreciated. Thank you in advance

This page seems to offer a MySQL function to return “time ago” based on comparing the current time to a specified field in the database, and would allow you to easily merge the string into the result set: http://stackoverflow.com/questions/7323883/sql-query-that-displays-time-ago-dates-like-one-week-ago-two-weeks-ago

Hi droopsnoot. Thank you for the reply. That looks quite ok. But what about minutes and hours. I have no idea how to approach this? Should I maybe ask thi question in the database section?

Thank you in advance

I found a very good library that is actually is doing evrything I need. This is the link to it. The only problem I have it is not converted to daylight saving time. How do I do that.

Thank you in advance

Can you expand on what you mean by it not converted to DST?

If it’s the “time ago” that you need (and I haven’t watched the video, my bandwidth is too slow for that), surely that would only change if the date/time pair that you’re comparing straddle a DST change date? So at 3am Sunday just gone (in the UK), a record posted at 23:00 on Saturday evening would actually be 5 hours ago, rather than 4 hours ago as a formula might return. But aren’t date/time values stored as GMT (OK then, UTC) and converted on display, so a comparison would still be correct?

Or did you mean something else? I’m thinking out loud, I haven’t done much with date / time comparisons as might be apparent.

Hi droopsnoot. thank you for the reply.
What I mean is this that all messages are displayin 1 hour behind. so a message posted 5 hours ago displays as 4 hours ago. A mesage just posted diplays -3600 seconds. Sorry to hear you couldn’t watch the video. This is the complete class anyway:

class convertToAgo {    
    function convert_datetime($str) {    
        list($date, $time) = explode(' ', $str);
        list($year, $month, $day) = explode('-', $date);
        list($hour, $minute, $second) = explode(':', $time);
        $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
        return $timestamp;
    }
    function makeAgo($timestamp){    
           $difference = time() - $timestamp;
           $periods = array("sec", "min", "u", "d", "w", "m", "j");
           $lengths = array("60","60","24","7","4.35","12","10");
           for($j = 0; $difference >= $lengths[$j]; $j++)
               $difference /= $lengths[$j];
               $difference = round($difference);
           if($difference != 1) $periods[$j];
               $text = "$difference $periods[$j]";
               return $text;
    }    
}

Maybe this gives you a better idea

My guess is that it comes down to what you pass into convert_datetime() - if that contains a time that is adjusted for DST, when it gets compared to time() (which always returns UTC, according to a note on the doc page) it’s going to be an hour different. So the key would seem to be to ensure that what you pass in is UTC, or alter the start of makeAgo() to ensure that the comparison time is the same.

Hi droopsnoot. I am not completely sure what you mean. I juimest changed the datetime of a test message to just now (I am in the netherlands and the time is 11:50).and this is what the time ago is displaying

-3356 sec

Then I adjusted the clock of my laptop (1 hour foward) and it gives me the right time. Does that make any sence?

OK, so you’re out of DST now, so that shouldn’t be relevant any more. So am I (in the UK) and for todays date and 11:50:00 I get “37 min”. Which is interesting as it’s around 11:28 here.

Adding this line to the start of my code makes it work correctly:

date_default_timezone_set("Europe/London");

which might be worth a try (obviously with your own selection).

This might be because the time() function always uses UTC to return the current timestamp, where mktime and other functions have to have a specific timezone set. You could add date_default_timezone_get() to see what it was using - mine was set to “Europe/Paris” for some reason, probably an installation thing.

Hi droopsnoot again thank you for the reply. Where in the class did you add that?

Thank in advance

I didn’t try it with the class as I haven’t really got any knowledge of them. I just put it before I called the functions:

<?php
echo(date_default_timezone_get()) . "\n";
date_default_timezone_set("Europe/London");
$x = "2016-11-02 11:20:00";
$ts = convert_datetime($x);
echo $ts . "\n";
$ag = makeAgo($ts);
echo $ag;

and then had the two function definitions outside of the class definition below that, which I won’t add to save scrolling. So perhaps it could go at the start of your main code, or in the class constructor.

That works great thanks a lot :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.