AS3 Code Snippet: Covert seconds to simple time stamp

October 15th, 2008 | Categories: Actionscript

What this code snippet allows is the ability to pass the number of seconds and return a simple time stamp in the form of “Weeks:Days:Hours:Minutes:Seconds” with the minimum return of “Minutes:Seconds”. A good use of this snippet is in media players to convert the duration of the media to a more readable time stamp.

/**
* Converts seconds to minutes and seconds
* @param number Number of seconds
* @return String of minutes and seconds (00:00)
*/
public function convertTime( number:Number ):String {
	number = Math.abs( number );
	var val:Array = new Array( 5 );
		val[ 0 ] = Math.floor( number / 86400 / 7 ); //weeks
		val[ 1 ] = Math.floor( number / 86400 % 7 );//days
		val[ 2 ] = Math.floor( number / 3600 % 24 );//hours
		val[ 3 ] = Math.floor( number / 60 % 60 );//mins
		val[ 4 ] = Math.floor( number % 60 );//secs
	var stopage:Boolean = false;
	var cutIndex:Number  = -1;
	for(var i:Number = 0; i < val.length; i++ ) {
		if( val[ i ] < 10 )
			val[ i ] = "0" + val[ i ];
		if( val[ i ] == "00" && i < ( val.length - 2 ) && !stopage ) {
			cutIndex = i;
		} else {
			stopage = true;
		}
	}
	val.splice( 0, cutIndex + 1 );
	return val.join( ":" );
}

Comments

TOP