Search code examples
actionscript-3flash-cs6

how to convert seconds to minutes:seconds in as3


hi to all i am new in action script 3 in flash cs6 im creating a game with a timer

i want to make the seconds to minutes:seconds format

example:

120 seconds to 2:00

this is my code:

    var countDownDec:Number = 1;
    var totalSecs = 120;
    var countDownSecs = totalSecs;

    counter.text = countDownSecs;

    var time:Timer = new Timer(countDownDec*1000);

    time.addEventListener(TimerEvent.TIMER, tick);




    time.reset();
    countDownSecs = totalSecs;
    counter.text = countDownSecs;
    time.start();


    var frameLbl:FrameLabel;

    function tick(e:TimerEvent):void {

        time.start();

        if(countDownSecs == 0){

            time.stop();
            countDownSecs = totalSecs;
            gotoAndPlay('timesUp');
            TimesUp.play();

        }
        else{
            countDownSecs = countDownSecs - countDownDec;
            counter.text = countDownSecs;
        }
    }

please help me to my problem


Solution

  • Divide by 60 and round down for minutes, modulo (%) 60 for seconds

    var totalSecs = 120;
    var minutes = Math.floor(totalSecs / 60);
    var seconds = totalSecs % 60;
    
    var timeInMinutesSeconds = minutes + ":" + seconds;
    

    EDIT:

    Try this:

    var countDownDec:Number = 1;
    var totalSecs:int = 120;
    var countDownSecs:int = totalSecs;
    counter.text = getCountDownSecsText(countDownSecs);
    
    var time:Timer = new Timer(countDownDec*1000);
    time.addEventListener(TimerEvent.TIMER, tick);
    
    var frameLbl:FrameLabel;
    
    function tick(e:TimerEvent):void {
        if(countDownSecs == 0) {
            time.stop();
            countDownSecs = totalSecs;
            gotoAndPlay('timesUp');
            TimesUp.play();
        } else {
            countDownSecs = countDownSecs - countDownDec;
            counter.text = getCountDownSecsText(countDownSecs);
        }
    }
    
    private function getCountDownSecsText(currentAmountSecs:int):String{
        var minutes:int = Math.floor(currentAmountSecs / 60);
        var seconds:int = currentAmountSecs % 60;
    
        var prependString:String = "";
        if( minutes > 9 ) {
            prependString = "0";
        }
    
        return prependString + minutes + ":" + seconds;
    }