How to Convert DateTime to X Minutes Ago in JQuery

Today I found a nice plugin with the help of which you can convert any date time on your HTML page to something similar to Gmail/Facebook updates – “5 minutes ago” or “a day ago”. The best part of this plugin is it auto updates the minutes as you’re on the webpage. So, if you have opened the page now and the date shows “1 minute ago”, after 5 minutes the same date will auto update to “6 minutes ago”. In this post, we will see how this plugin works and write a simple HTML using the plugin.

To start with, you can download the timeago plugin from here.This plugin depends on jquery. so the very 1st thing is to include jQuery in our code and then the plugin Javascript.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="jquery.timeago.js"></script>

Once the plugin files are loaded, you can use the plugin’s timeago() function in any of the following ways :

var date = $.timeago(new Date()); //Displays 'less than a minute ago'
var date = $.timeago('2014-05-04'); //Displays 'a day ago'

You can also call the timeago() function on a specific class on your page as below :

//This will modify the date time on all elements having class as 'time'
$(document).ready(function(){
$(".time").timeago();
});

Keep learning and sharing! Cheers! 

Ebook Download
View all
Learn
View all
Think. Innovate. Grow.