techno
techno

Reputation: 192

Moment.js always gives "a few seconds ago"

I have this script time.js

function changeTime(){
  $('p.text-muted').each(function(index, el) {
    $str = moment($(el).text()).fromNow();
    console.log($str);
    $(el).html('<i class="fa fa-clock-o"></i>  '+$str);
  });
}
changeTime();
setInterval(update, 1000*60);

This is one of the places where I'm calling changeTime():

<p class="small text-muted" id="t<?php echo($tweet['tid']);?>"><i class="fa fa-clock-o"></i> <?php echo($tweet['ttime']); ?></p>

When changeTime() is called for the first time, the values get set properly. But later on, it gives "a few seconds ago".

I understand the problem that on later calls, it becomes a moment('4 days ago'). fromNow() becomes "a few seconds ago". So how do I convert this 4 days ago to actual time and then again call .fromNow()? I couldn't find the exact method. Please help.

Thank you :)

Upvotes: 0

Views: 1624

Answers (1)

Mudaser Ali
Mudaser Ali

Reputation: 4309

First of all there is an error in your pasted code setInterval(update, 1000*60); it should be setInterval(changeTime, 1000*60);

Secondly please save timestamp in an attribute instead of inside the div

<p class="small text-muted" id="t<?php echo($tweet['tid']);?>" data-timestamp="<?php echo($tweet['ttime']); ?>"><i class="fa fa-clock-o"></i> <?php echo($tweet['ttime']); ?></p>

Updated JS code:-

function changeTime(){
  $('p.text-muted').each(function(index, el) {
    $str = moment($(el).data('timestamp')).fromNow();
    console.log($str);
    $(el).html('<i class="fa fa-clock-o"></i>  '+$str);
  });
}
changeTime();
setInterval(changeTime, 1000*60);

Upvotes: 2

Related Questions