Time format from seconds in AS3 10

Here’s a quick and dirty class for converting seconds into the proper hours : minutes : seconds display format, with optional resolution setting (hours/minutes/seconds). Defaults to hours. Sample implementation:

trace(TimeFormat.formatTime(200, TimeFormat.SECONDS));

outputs “0:03:20″. Full class after the break.

package {
public class TimeFormat{
public static const HOURS:uint = 2;
public static const MINUTES:uint = 1;
public static const SECONDS:uint = 0;
public function TimeFormat() {
}
public static function formatTime(time:Number, detailLevel:uint = 2):String {
var intTime:uint = Math.floor(time);
var hours:uint = Math.floor(intTime/ 3600);
var minutes:uint = (intTime - (hours*3600))/60;
var seconds:uint = intTime -  (hours*3600) - (minutes * 60);
var hourString:String = detailLevel == HOURS ? hours + ":":"";
var minuteString:String = detailLevel >= MINUTES ? ((detailLevel == HOURS && minutes <10 ? "0":"") + minutes + ":"):"";
var secondString:String = ((seconds < 10 && (detailLevel >= MINUTES)) ? "0":"") + seconds;
return hourString + minuteString + secondString;
}
}
}

10 thoughts on “Time format from seconds in AS3

  1. Eerk Feb 16, 2010 8:45 am

    Saved me a lot of time! Thanks!

  2. Sebastian Oct 13, 2010 8:28 pm

    You’re a legend!. Cleanest and most optimized time format converter class I found around Google’s first page of results… that says a lot.

    When it comes to math I tend to get a little bit lazy haha …

    Cheers again!

  3. Shaun Thomson Nov 29, 2010 1:11 am

    Hi

    This outputs “20″ instead of “0:03:20″ for me.

    Is there something else I need to do to get it working?

    Thanks

  4. jermbo May 23, 2011 4:54 pm

    this is exactly what i needed. Thank you!!

    for my own understanding can you explain why you are dividing and multiplying by 3600. And what does the % do in terms of math functions.

    Thank your for your time!

  5. Jeff dePascale May 23, 2011 6:08 pm

    @jermbo:

    We are working with seconds, so 3600 is equivalent to 1 hour in total seconds (60 seconds per minute * 60 minutes).

    % is the modulo operator, better described here:

    http://en.wikipedia.org/wiki/Modulo_operation

    basically you get the remainder of a calculation. So 5%2 would be 1, since 5 divided by 2 is 2 with a remainder of 1. Hope that helps :)

  6. Pingback: AS3 Flash Counter Using the Timer Class and Formatting Time in Minutes | Ali Qureshi's Blog

  7. Romeo Mar 31, 2012 12:47 am

    Very nice, thank you :)

  8. Reed Aug 15, 2012 8:05 am

    Thanks a lot dude!

Leave a Reply