jQuery Time ago from a timestamp?

前端 未结 4 833
夕颜
夕颜 2021-02-06 08:31

Below is a really nice time ago plugin for jQuery, very similar to what they use here on SO. The problem for me is that it uses this to convert time.

4条回答
  •  滥情空心
    2021-02-06 09:22

    Here is something in JavaScript using nothing but Unix timestamps.

    var d1;
    var d2;
    d1 = (new Date()).getTime(); setTimeout( function() { d2 = (new Date()).getTime(); }, 5000 );
    var secondsElapsed = (d2 - d1) / 1000;
    secondsElapsed; // 5 seconds
    

    Now, you can either store a timestamp in a JavaScript variable in the same scope as your "timeago" function, or your can store it in an HTML element. As mentioned, the time element is an HTML 5 element. You could do something like:

    
    
    

    Then maybe you have a comment item like:

    
    

    Lorem ipsum et dolor...123456

    You could then get the timestamp for a comment by (assuming jQuery since you mentioned it):

    
    var tstamps = $('.comment .timestamp'); // array of comment timestamps
    var timeago = ( (new Date()).getTime() - tstamps[0].html() ) / 1000;
    

    It's a bit hackish, but it would work (if I did it right).

提交回复
热议问题