phpjquerytimeago

Timeago giving me wrong amount of time


I'm trying to use timeago to display how long ago an action was done on my website.

I'm using an ajax request to add rows to a table, and then once all the rows are added, I'm activating the timeago again. I have a function called fill_table() which gathers some row data from a php script and then loops through the data adding rows to the table.

function fill_table() {
    $.ajax({
        ...
        success : function(data) { 
            var table = $('#table_body');
            table.empty();
            $.each(data, function( index, value ) {

                var date = new Date(new Date(value.last_updates).toLocaleString("en-US", {timeZone: "America/Chicago"})).toISOString();

                var elem = '\
                    <tr>\
                        <td><a target="_blank" href="' + value.name + '">' + value.name + '</a></td>\
                        <td>' + value.market_value + '</td>\
                        <td>' + value.lowest_cost + '</td>\
                        <td>' + value.biggest_md_format + '</td>\
                        <td><time class="timeago" datetime="' + date + '"></time></td>\
                    </tr>\
                ';
                table.append(elem);
            });
            $("time.timeago").timeago();                
        },
        error : function(request,error)
        {
            console.log("Request: "+JSON.stringify(request));
        }
    });
}

Now, for some reason this is telling me "6 hours ago" for timestamps that should only be 8-12 minutes old at the most.

As you can see in the code, I've declared date using some crazy toLocaleString thing just to make sure it was the right timezone, I also already set the PHP header in my controller

date_default_timezone_set('America/Chicago');

Inspecting the timeago element gives me this

<time class="timeago" datetime="2019-03-03T12:56:28.000Z">about 6 hours ago</time>

Which the datetime is correct, 12:56 AM CST (America/Chcago), but that is only about 10 minutes ago.

So I'm at a loss, I've tried fixing timezone issues with no luck and don't know what else to do.

How can I make timeago read the correct amount of time?


Solution

  • That datetime is not correct. That Z at the end designates it as UTC time zone, not your local time zone. So timeago correctly gives you a difference of multiple hours with that time in UTC.

    Check your inputs and that conversion logic in JS.