Another short one from me today. I have been very busy with work and moving flat recently which means I haven’t been able to post as often as I’d like and as often as I’m suppose to give the rather simple rules of the postaweek 2011 challenge. I fell behind whilst away and haven’t been able to catch up. Sorry about that.

On to this post.

One of the things I needed to do for work was to display some dates in a more friendly and understandable way. Seen as it wasn’t imperative for the user to know the exact, to the second time of creation I decided I wanted to display them in a similar way to sites that display them like “a year ago” and “2 weeks ago”. After a quick google I couldn’t find exactly what I needed — I’m sure if I’d’ve continued my search something suitable would’ve been found but I thought it would be a quick interesting problem to solve.

I wrote the following javascript to do the job. See what you think:

var simpleDate = (function() {
	var measures = {
		second: 1,
		minute: 60,
		hour: 3600,
		day: 86400,
		week: 604800,
		month: 2592000,
		year: 31536000
	var chkMultiple = function(amount, type) {
		return (amount > 1) ? amount + " " + type + "s":"a " + type;
	return function(thedate) {
		var dateStr, amount, denomination,
			current = new Date().getTime(),
			diff = (current - thedate.getTime()) / 1000; // work with seconds
		if(diff > measures.year) {
			denomination = "year";
		} else if(diff > measures.month) {
			denomination = "month";
		} else if(diff > measures.week) {
			denomination = "week";
		} else if(diff > {
			denomination = "day";
		} else if(diff > measures.hour) {
			denomination = "hour";
		} else if(diff > measures.minute) {
			denomination = "minute";
		} else {
			dateStr = "a few seconds ago";
			return dateStr;
		amount = Math.round(diff/measures[denomination]);
		dateStr = "about " + chkMultiple(amount, denomination) + " ago";
		return dateStr;

I hope you find it useful, and if you have any ideas about improvements then please go ahead and post them in the comments section, I’d love to hear them.

I’ve behind thinking about rewriting it using the Date.prototype object but I’m not sure whether it would be worth it. If I do though I’ll make sure I post the code here for those that are interested.