Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created October 4, 2012 20:01
Show Gist options
  • Save amcdnl/3836051 to your computer and use it in GitHub Desktop.
Save amcdnl/3836051 to your computer and use it in GitHub Desktop.
Date/Time Ago + jQuery Globalize

Date/Time Ago + jQuery Globalize

Formats Date/Time stamps to be relative using jQuery Globalize framework.

The following DOM would result in a relative time formatted string:

<span class="timeago" data-time="1349381619452"></span>

We extend the Globalize code to add this timeago helper.

jQuery.extend(Globalize, {

	timeago:function(date){
		var distance = (new Date().getTime() - date.getTime()),
			seconds = Math.abs(distance) / 1000,
			minutes = seconds / 60,
			hours = minutes / 60;

		var words = seconds < 45 && Globalize.localize('%lbl.time.justnow') ||
			seconds < 90 && Globalize.localize('%lbl.datetime.relative.past', ['1', lz('%lbl.datetime.minute')]) ||
			minutes < 45 && Globalize.localize('%lbl.datetime.relative.past', [Math.round(minutes), lz('%lbl.datetime.minutes')]) ||
			minutes < 90 && Globalize.localize('%lbl.datetime.relative.past', ['1', lz('%lbl.datetime.hour')]) ||
			hours < 24 && Globalize.localize('%lbl.datetime.relative.past', [Math.round(hours), Globalize.localize('%lbl.datetime.hours')]) ||
			hours < 42 && (Globalize.localize('%lbl.datetime.yesterday') + " " + this.format(date, 't')) ||
			this.format(date,'d') + " " + this.format(date, 't');
			
		return words;
	}

});

Then set a interval to run and update the dates ...

setInterval(function() {
	var elms = $('.timeago');
	elms.each(function(){
		var elm = $(this),
			date = elm.attr('data-time'),
			current = elm.html()
			timeago = Globalize.prettyDateTime(date);
			
		if(current != timeago){
			elm.html(timeago);
		}
	});
}, 10000);

Add the new keys to your Globalize dictionary...

Globalize.addCultureInfo('en-US', {
	messages: {
		"%lbl.time.justnow" : "Just Now"
	}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment