Search code examples
javascriptjquerysocket.iotimeago

Jquery Timeago NaN Years ago from .attr


To start, I'm finally posting after battling for a while with this.

Basically, I'm using Socket.IO to create a messenger for a site im working on. I'm having an issue with the timeago plugin displaying NaN years ago as its output.

After googling around, i see that the timeago plugin requires a pretty specfic date format, or a Java Date() object.

Here's my code..

socket.on('chat.message', function (data) {
  data = JSON.parse(data);
  if (data.hasOwnProperty('system')) {
    toastr["success"](data.msg);
  } else {
    $chat.append(
      '<li class="left clearfix">' +
      '<span class="chat-img pull-left">' +
      '<img src="https://www.gravatar.com/avatar/?d=mm&amp;s=40" alt="User Avatar" class="img-circle" width="50" />' +
      '</span>' +

      '<div class="chat-body clearfix">' +
      '<div class="header">' +
      '<strong class="primary-font">' + data.nickname + '</strong>' +
      '<small class="pull-right text-muted time" data-time="' + data.timeSent + '">' +
      '<span class="glyphicon glyphicon-time"></span>' + $.timeago(data.timeSent) +
      '</small>' +
      '</div>' +
      '<p>' + data.msg + '</p>' +
      '</div>' +
      '</li>'
    );
    $('.panel-body').animate({scrollTop: $chat.height()});
  }
});

function updateTimes() {
  $('.time').each(function () {
    var time = $.timeago($(this).attr('data-time'));
    $(this).html(time);
  });
}
setInterval(function () {
  updateTimes();
}, 3000);

So as you can see, each message element appended onto the page has the timeago output, and the original time sent stored in an attribute for my function to update using updateTimes().

When the message is first received, everything is fine. However when i use the attribute's value and pass that to timeago, this is where everything goes wrong.

From searching around, i thought i might be able to do the follow:

function updateTimes() {
  $('.time').each(function() {
    var time = new Date($(this).attr('data-time'));
    $(this).html($.timeago(time));
  });
}

Although this didnt work either.

....Edit....

I forgot to mention how i'm setting the time at first..

var d = new Date();
var time = d.getTime();

Hopefully this is obvious for someone, unfortunaly my javascript knowledge is lacking!

Any help is greatly appreciated.

Ok, so this has now been resolved.

Seems you can't pass Date() a string, so i had to

var time = new Date(parseInt($(this).attr('data-time')));

Many thanks to @amklose


Solution

  • Ok, so this has now been resolved.

    Seems you can't pass Date() a string, so i had to

    var time = new Date(parseInt($(this).attr('data-time')));

    Many thanks to @amklose