0

I am working on a page that pulls data from DB. PHP time() is captured and saved to the DB alongside user contents.

I want to be about to subtract the capturedTime from the current time using JavaScript and display how long the post has been made in hr : min : s and should be live.

HTML:

<div class = 'responses'>
   <p class = 'capturedTime' style='display: none;'>123456789</p>
</div>

jQuery:

$(document).on('click', '.responses', function () {
     $this = $( this );
     timeC = $this.prev('.capturedTime').text();
     timeNow = $.now()
     timeLapsed = ( timeNow - timeC )/1000;
     seconds = timeLapsed/60;
     mins = seconds/60;
     hrs = mins/24;
     if ( timeLapsed !== NaN ){
         alert(seconds + '------' + mins + '---' + hrs);
     }
 });
4
  • $.now() will give you milliseconds. PHP's time() gives you seconds; that's one thing you'll have to sort out. Commented May 28, 2014 at 9:51
  • @oGeez: If I do that, how can I make it count up? Commented May 28, 2014 at 9:54
  • Apologies I misunderstood the idea of your code. Are you just testing to see how long it has been since the element was first loaded? I wouldn't want to compare timestamps from the server with those on the client. Commented May 28, 2014 at 9:58
  • No. I am trying to display how long the post has been made. Just like that of Twitter. Commented May 28, 2014 at 10:00

2 Answers 2

1

I suggest you to change your code this way:

Fiddle

<body>
    <div class='responses'>
        <p class='capturedTime' data="1401270715145"></p>
    </div>
</body>






var $times, timer;

$times = $('.capturedTime');
timer = setInterval(function () {
    var i, len, cache, value, now, minutes, seconds;

    for (i = 0, len = $times.length; i < len; i = i + 1) {
        cache = $times.eq(i);
        now = new Date().getTime();
        value = new Date(now - parseInt(cache.attr("data")));
        minutes = value.getMinutes();
        seconds = value.getSeconds();
        cache.html("m:" + minutes + " ss:" + seconds);
    }

}, 1000);
Sign up to request clarification or add additional context in comments.

1 Comment

Offcourse you can customize the shown timing as well as refresh rate as you like.
1

try this :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://timeago.yarp.com/jquery.timeago.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function(){
        var lastUpdate = new Date($(".capturedTime").html()*1000)
        alert($.timeago(lastUpdate));
         });                
</script>

or visit this page

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.