jQuery Time ago from a timestamp?

前端 未结 4 834
夕颜
夕颜 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 08:56

    I had the same problem. I'm using Unix timestamps which are generated from PHP, so I decided to do a quick hack and extend the parsing function of jQuery timeago to handle timestamps additionally. Works like a charm. Simply look for the Parse function at around line 79 in the jquery.timeago.js file, and replace with the following:

      parse: function(iso8601) {
      if ((iso8601 - 0) == iso8601 && iso8601.length > 0) { // Checks if iso8601 is a unix timestamp
        var s = new Date(iso8601);
        if (isNaN(s.getTime())) { // Checks if iso8601 is formatted in milliseconds
          var s = new Date(iso8601 * 1000); //if not, add milliseconds 
        }
        return s;
      }
    
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    

提交回复
热议问题