Quantcast
Channel: Code, Hacks and Other Nerdy Things » Actionscript
Viewing all articles
Browse latest Browse all 3

Dealing with UNIX time in ActionScript 3.0

$
0
0

If you’ve got flash communicating with a server, using UNIX time can be more robust then strings. UNIX time is often used in SQL databases and on servers. Using an int for all numbers means you don’t have to deal with daylight savings and other events.

To convert a UNIX time into an ActionScript Date object:

/**
* converts UNIX time to flash Date()
* @param time number - unix time to convert
* @return Date object
*/
public function getDate(time:Number):Date {
	var mtime:Date = new Date(1970, 0, 1, 0, 0, 0);
	// Add on the number of seconds (this is our unix timestamp)
	mtime.setSeconds(time); 
	return mtime;
} 

After you have a data object that was set by a unix stamp, you can treat it like a date object.

Sadly Adobe’s toString() function makes the date object ugly and unreadable. Date.toString() returns something like: Fri Apr 15 02:44:33 GMT+1200 2011. This is:

  • horrible to look at
  • requires users to lookup GMT to get their local time
  • will put the users off reading nearby text

It may seem trivial to make it readable, but you might as well not have it if it’s not being read. The fix is simple: take the date and work out how long ago it happened.

To make a UNIX time more readable:

/**
* converts a UNIX time to a human readable time scale (eg 20 mins ago) 
* @param time time in seconds since 1970, 0, 1 (UNIX time)
* @returns a string with minutes, hours or days ago event happened
*/
public function human_time( time:uint ) : String {
	var now:Date = new Date();
	var diff = now.time / 1000 - time;
			
	if (diff <= 3600) {
		var mins:Number = Math.round(diff / 60);
		if (mins <= 1) {
			return "1 min";
		}
		return mins +" mins";
	} else if ((diff <= 86400) && (diff > 3600)) {
		var hours:Number = Math.round(diff / 3600);
		if (hours <= 1) {
			return "1 hour";
		}
		return hours+" hours";
	} else if (diff >= 86400) {
		var days:Number = Math.round(diff / 86400);
		if (days <= 1) {
			return "1 day";
		}
		return days + " days";
	}
	return "unknown";
}

This will return something like 3 hours, 20 days or 2 mins. The user will more likely read it and know how long ago it happened.

Some notes: the local computer must have the accurate time and it doesn’t accomodate times in the past. Modern computers sync using the net this shouldn’t be a problem and a simple mod can accommodate times in the past


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images