Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery time ago with unix epoch

Tags:

jquery

django

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!

like image 569
prostock Avatar asked Sep 20 '10 23:09

prostock


2 Answers

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?

like image 135
David Xia Avatar answered Sep 20 '22 19:09

David Xia


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.

like image 28
Marc B Avatar answered Sep 22 '22 19:09

Marc B