« Adobe Feeds Data Problem | Main | New version of PixelWindow »

June 1, 2009

ActionScript function for turning a date into a time interval

While working on a small Twitter utility, I wrote a function to turn a date into a time interval string. For instance, rather than formatting the date, it returns strings like "Just posted," "6 minutes ago," "4 hours ago," or "20 days ago". It's not a complex function, but I thought I'd post it here in case it might save someone a few minutes of coding. The less time we spend writing code someone else has already written, the more time we can spend innovating.

private function formatDate(d:Date):String
{
	var now:Date = new Date();
	var diff:Number = (now.time - d.time) / 1000; // convert to seconds
	if (diff < 60) // just posted
	{
		return "Just posted";
	}
	else if (diff < 3600) // n minutes ago
	{
		return (Math.round(diff / 60) + " minutes ago");
	}
	else if (diff < 86400) // n hours ago
	{
		return (Math.round(diff / 3600) + " hours ago");
	}
	else // n days ago
	{
		return (Math.round(diff / 86400) + " days ago");
	}
}

Posted by cantrell at June 1, 2009 10:42 AM

Comments

Thanks. This just saved me some valuable time. I needed this function.

-D

Posted by: Danny at June 2, 2009 11:09 AM




Remember Me?

(you may use HTML tags for style)