开发者

jquery time ago with unix epoch

I'm using django currently and outputting the date in seconds from the unix epoch. How do I use jquery time ago with unix epoch?

I see this开发者_如何学运维 example: January 10, 2015

<abbr class="timeago" title="2015-01-10T15:00:00Z">January 10, 2015</abbr>

but can i do something like:

<abbr class="timeago" title="2015-01-10T15:00:00Z">{{UNIX_EPOCH_IN_SECONDS}}</abbr>

Thanks!


You don't need to convert your unix timestamp to ISO. Hal posted a piece of code modifying jQuery's timeago plugin that worked for me. Simply replace timeago's parse() function at line 89 with this:

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);
},

jQuery Time ago from a timestamp?


You can initialize a Date object with a unix timestamp, but Javascript's date expects time in milliseconds, so it's simply:

var d = new Date(<?php echo date('U') ?>000);

which turns into something like:

var d = new Date(1285027311000);

It'll also parse most standard textual date formats, must as PHP's strtotime() will, though you'll have to test exactly how forgiving it is.


The Date() constructor can take the number of milliseconds since 00:00:00 UTC 1/1/1970, and timeago can be used with a Date object. So:

jQuery.timeago(new Date(unixSeconds * 1000));

Should work.


Step 1 First add JQuery and timeago jquery plugin

<script type="text/javascript" src="https://timeago.yarp.com/jquery.timeago.js"></script>

Step 2 No need to write anything in between tags

<abbr class="timeago" title="2015-01-10T15:00:00Z"></abbr>

Step 3 Use the following JQuery code

var postAddDate = new Date($(".timeago").attr("title"));
var timeAgo = jQuery.timeago(postAddDate);
$(".timeago").html(timeAgo);

Memory efficient version

$(".timeago").html(jQuery.timeago(new Date($(".timeago").attr("title"))));

See in Codepen

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜