Return to Snippet

Revision: 35094
at November 2, 2010 13:14 by CreativeAddiction


Updated Code
//###############################
//Usage:
var myRelativeTime:String = timestampToRelative("Sun Oct 24 20:07:33 +0000 2010");
//returns a string
//###############################

function timestampToRelative(timestamp:String):String {
	//--Parse the timestamp as a Date object--\\
	var pastDate:Date = new Date(timestamp);
	//--Get the current data in the same format--\\
	var currentDate:Date = new Date();
	//--seconds inbetween the current date and the past date--\\
	var secondDiff:Number = (currentDate.getTime() - pastDate.getTime())/1000;

	//--Return the relative equavalent time--\\
	switch (true) {
		case secondDiff < 60 :
			return int(secondDiff) + ' seconds ago';
			break;
		case secondDiff < 120 :
			return 'About a minute ago';
			break;
		case secondDiff < 3600 :
			return int(secondDiff / 60) + ' minutes ago';
			break;
		case secondDiff < 7200 :
			return 'About an hour ago';
			break;
		case secondDiff < 86400 :
			return 'About ' + int(secondDiff / 3600) + ' hours ago';
			break;
		case secondDiff < 172800 :
			return 'Yesterday';
			break;
		default :
			return int(secondDiff / 86400) + ' days ago';
			break;
	}
}

Revision: 35093
at November 2, 2010 13:12 by CreativeAddiction


Initial Code
//###############################
//Usage:
timestampToRelative("Sun Oct 24 20:07:33 +0000 2010");
//returns a string
//###############################

function timestampToRelative(timestamp:String):String {
	//--Parse the timestamp as a Date object--\\
	var pastDate:Date = new Date(timestamp);
	//--Get the current data in the same format--\\
	var currentDate:Date = new Date();
	//--seconds inbetween the current date and the past date--\\
	var secondDiff:Number = (currentDate.getTime() - pastDate.getTime())/1000;

	//--Return the relative equavalent time--\\
	switch (true) {
		case secondDiff < 60 :
			return int(secondDiff) + ' seconds ago';
			break;
		case secondDiff < 120 :
			return 'About a minute ago';
			break;
		case secondDiff < 3600 :
			return int(secondDiff / 60) + ' minutes ago';
			break;
		case secondDiff < 7200 :
			return 'About an hour ago';
			break;
		case secondDiff < 86400 :
			return 'About ' + int(secondDiff / 3600) + ' hours ago';
			break;
		case secondDiff < 172800 :
			return 'Yesterday';
			break;
		default :
			return int(secondDiff / 86400) + ' days ago';
			break;
	}
}

Initial URL
http://bit.ly/as3twitter

Initial Description
Whilst building an AS3 twitter widget i developed this code to change the timestamp formatted like this: Sun Oct 24 20:07:33 +0000 2010 to something much more usable such as '43 minutes ago' or 'about 4 days ago'

Initial Title
Relative Time from Timestamp

Initial Tags


Initial Language
ActionScript 3