Convert seconds to minutes and seconds in Actionscript 3 - actionscript-3

I'm working with the youtube API and I'm getting the current time on the video as seconds.
What I want to do is to convert them into this: MM:SS
I've tried to google and try different things by myself but nothing seemed to work and be efficient.
I'll be glad to see how it can be done in a good and efficient way thanks in advance!

Something like:
var formattedTime =
(Math.floor(seconds/60)) + ":" + // minutes
(seconds % 60 >= 10 ? "": "0") + // padding for seconds if needed
(seconds % 60)); // seconds

here is a little class I use all the time just for what you need. I've also added a timecodes to seconds method. Simply use it like Timecodes.secondsToTimecode(634); which will output 00:10:34
package com.ronnieswietek.utils
{
public class Timecodes
{
public function Timecodes()
{
}
public static function timecodeToSeconds(tcStr:String):Number
{
var t:Array = tcStr.split(":");
return (t[0] * 3600 + t[1] * 60 + t[2] * 1);
}
public static function secondsToTimecode(seconds:Number):String
{
var minutes:Number = Math.floor(seconds/60);
var remainingSec:Number = seconds % 60;
var remainingMinutes:Number = minutes % 60;
var hours:Number = Math.floor(minutes/60);
var floatSeconds:Number = Math.floor((remainingSec - Math.floor(remainingSec))*100);
remainingSec = Math.floor(remainingSec);
return getTwoDigits(hours) + ":" + getTwoDigits(remainingMinutes) + ":" + getTwoDigits(remainingSec);
}
private static function getTwoDigits(number:Number):String
{
if (number < 10)
{
return "0" + number;
}
else
{
return number + "";
}
}
}
}

var timeStr:String;
//Video's length >= 1 hour
if( seconds >= 60*60 ){
//Format-> H:MM:SS
timeStr = (""+Math.floor(seconds/(60*60))) + //Hours
":"+
("0"+Math.floor((seconds%(60*60))/60)).substr(-2)+ //Minutes
":"+
("0"+(seconds%60)).substr(-2); //Seconds
}else{
//Format-> MM:SS
timeStr = ("0"+Math.floor(seconds/60)).substr(-2)+ //Minutes
":"+
("0"+(seconds%60)).substr(-2); //Seconds
}

Something a little easier to read to get your head around it:
var seconds:int = 200;
var minutes:int = 0;
while(seconds >= 60)
{
seconds -= 60;
minutes ++;
}
trace(minutes, seconds);
The leading zeros part can be done like so:
var secStr:String = String(seconds);
var minStr:String = String(minutes);
secStr = (secStr.length == 1) ? "0" + secStr : secStr;
minStr = (minStr.length == 1) ? "0" + minStr : minStr;
trace(minStr + ":" + secStr);

Related

Countdown Timer in AS3

I'm testing the opposite script as a countdown timer, and there's a type error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event#33d6b881f29 to flash.events.TimerEvent.
var goalTimerScore: int = Math.floor(Math.random() * 101) + 20;
var Minutes:Number = Math.floor(Math.random() * 11);
var Seconds:Number = Math.floor(Math.random() * 60);
timerMin_txt.text = String(Seconds);
timerSec_txt.text = String(Minutes);
timerWatch.addEventListener(Event.ENTER_FRAME, countTimer);
timerWatch.play();
function countTimer(e:TimerEvent):void {
if (timerWatch.currentFrame == 61) {
Seconds--;
if (Seconds > 59) {
Seconds = 0;
timerSec_txt.text = "0" + Seconds;
Minutes--;
if (Minutes > 10) {
timerMin_txt.text = "" + Minutes;
} else {
timerMin_txt.text = "0" + Minutes;
}
if (Minutes == 0 && Seconds == 0) {
timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
timer.stop();
gotoAndPlay("gameover_Hidden3");
return;
}
}
else {
if (Seconds >= 10) {
timerSec_txt.text = "" + Seconds;
} else {
timerSec_txt.text = "0" + Seconds;
}
}
}
}
Any ideas how to solve this?
You have the wrong function parameters, they should be:
function countTimer(e:Event):void {
As a suggestion, running a timer off the frame rate can be pretty inconsistent as it relies on a constant frame rate. Probably better to use a time based approach.
You can use the Timer class for a basic approach. There is an example in the asdocs of a count down.
https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html
function countTimer(e: Event): void {
if (timerWatch.currentFrame == 61) {
Seconds--;
if (Seconds < 0) {
Minutes--;
Seconds = 59;
}
if (Minutes == 0 && Seconds == 0) {
timerWatch.removeEventListener(Event.ENTER_FRAME, countTimer);
timerWatch.stop();
gotoAndPlay("gameover_Hidden3");
return;
}
if (Minutes >= 1 && Seconds == 0) {
if (Minutes == 0) {
timerMin_txt.textColor = 0xFF0000;
timerSec_txt.textColor = 0xFF0000;
}
}
}
if (Seconds < 10) {
timerSec_txt.text = "0" + Seconds;
} else {
timerSec_txt.text = "" + Seconds;
}
if (Minutes < 10) {
timerMin_txt.text = "0" + Minutes;
} else {
timerMin_txt.text = "" + Minutes;
}
}
A crucial thing for timer accuracy is the stage.frameRate property. Without maxing it out, accuracy will be multiples of 60 Hz.
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.getTimer;
import flash.utils.Timer;
stage.frameRate = 1000;
const t:Timer = new Timer(0);
t.addEventListener(TimerEvent.TIMER, t_h);
t.delay = 10000; //10 seconds
timestamp = getTimer();
t.start();
public function t_h(e:TimerEvent):void {
trace("countdown complete")
trace(getTimer() - timestamp)
t.stop();
}

Convert a decimal number to a fraction AS3

I'm trying to get to convert the decimals to a fraction so for example, I had written something such as var _pow:int = Math.pow(base,i) and if i turned out to be a negative number it would give out a decimal (example: 3 ^ -2) and I'm currently stuck trying to find a way to turn _pow into a franction (so _pow out of a 100) so I tried to do var _pow:int = Math.pow(base,i) * 100 which should stop it from being a decimal but it's not showing in the dynamic text, and this only happens if i is negative
package{
import flash.display.*;
import flash.events.MouseEvent;
public class name_ extends MovieClip{
public function _name_(){
btn.addEventListener(MouseEvent.CLICK, input)
base.restrict = "0-9\\.\\-";
pow.restrict = "0-9\\.\\-";
answer.multiline = true;
}
private function input(event:MouseEvent):void{
var pow = pow.text;
var base = base.text;
var answerText:String = "";
if(pow > 0){
for(var i = 1; i <= pow; i++){
_pow = Math.pow(base,i);
answerText += ("\n" + base + " exposant(power) " + i + " = "+ _pow );
answer.text = answerText;
}
}else{
for(i = 1; i <= pow; i++){
var _pow:int = Math.pow(base,i) * 100
answerText += ("\n" + base + " exposant(power) " + i + " = "+ _pow );
answer.text = answerText; //Dynamic text
}
}
}
}
}
Have you tried using an "if" statement? Something like if(i <= 0){code}.
You can also try using the Math.floor(number to be rounded down); or Math.ceiling(number to be rounded up)

How to have Timer Count Down AS3

I have a Timer that I am trying to get to countdown instead of up. I worked with this code years ago and can't seem to figure out how to make it count down from 5 minutes.
I've only tried messing with the variables.
Here are my variables etc:
tCountTimer = new Timer(100);
tCountTimer.addEventListener(TimerEvent.TIMER, timerTickHandler);
timerCount = 0;
tCountTimer.start();
Here are my Functions to Count:
private function timerTickHandler(e:Event):void
{
timerCount += 100;
toTimeCode(timerCount);
}
private function toTimeCode(milliseconds:int):void
{
this.milliseconds = milliseconds;
//create a date object using the elapsed milliseconds
time = new Date(milliseconds);
//define minutes/seconds/mseconds
minutes = String(time.minutes + 5);
seconds = String(time.seconds);
miliseconds = String(Math.round(time.milliseconds) / 100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+ minutes : minutes;
seconds = (seconds.length != 2) ? '0' + seconds : seconds;
//display elapsed time on in a textfield on stage
playScreen.timeLimitTextField.text = minutes + ":" + seconds;
}
It counts up perfect but just can't get it to time down from 5 minutes. All help is much appreciate.
Didn't test that, but I hope the idea is absolutely clear.
// Remember the time (in milliseconds) in 5 minutes from now.
var endTime:int = getTimer() + 5 * 60 * 1000;
// Call update function each frame.
addEventListener(Event.ENTER_FRAME, onFrame);
function onFrame(e:Event):void
{
// How many milliseconds left to target time.
var aTime:int = endTime - getTimer();
// Fix if we are past target time.
if (aTime < 0) aTime = 0;
// Convert remaining time from milliseconds to seconds.
aTime /= 1000;
// Convert the result into text:
// aTime % 60 = seconds (with minutes stripped off)
// aTime / 60 = full minutes left
var aText:String = ze(aTime / 60) + ":" + ze(aTime % 60);
// Do whatever you want with it.
trace(aText);
}
// Function to convert int to String
// and add a leading zero if necessary.
function ze(value:int):String
{
return ((value < 10)? "0": "") + value.toString();
}

Stop clock on pause button

I have a "clock" counting down the time of the game (from 9 seconds to 0 seconds). I have a button that pauses the game, so I want to freeze de clock and when I click to play, the game continuos from that second that I frozen. But I don't have any idea how to do this! Can you help me please?
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
var t:uint = getTimer();
var dt:uint = 9000 - t;
var totseconds:uint = Math.floor(dt/1000);
var minutes:uint = Math.floor(totseconds/60);
var seconds:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = seconds < 10 ? "0" + seconds : seconds;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
...somegame code...
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
...some game code
}
You have two choices at least:
1-Andre's answer;
2-my answer:
import flash.events.Event;
var dt:int = 9000
var diff:Number=0;
var prevDiff:Number=0;
var currentTime:Number=0;
var t:uint=0;
var totseconds:int=0;
var minutes:int=0;
var seconds:int=0;
var minsWithZ;
var secsWithZ;
var running:Boolean=true;
var time;
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
if(dt<1){dt=1;menuPause(null)}
trace(running);
totseconds= Math.floor(dt/1000);
minutes= Math.floor(totseconds/60);
seconds= Math.floor(totseconds%60);
minsWithZ = minutes < 10 ? "0" + minutes : minutes;
secsWithZ = seconds < 10 ? "0" + seconds : seconds;
time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
if(running){
t= getTimer()-diff-prevDiff;
dt=5000- t;
}else{
diff=getTimer()-currentTime;
}
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
voltar.addEventListener(MouseEvent.MOUSE_UP, reset);
function menuPause(e:Event){
running=false;
currentTime=getTimer();
prevDiff+=diff;
}
function menuPlay (e:Event){
running=true;
}
function reset(){
running=true;
prevDiff+=9000;
}
A little explaination on code:
getTimer() returns the miliseconds from when you opened the app and
You can't Pause "getTimer()"
but you can get the time that game is paused and subtract from getTimer().
variable "diff" does that here.
and "currentTime" is when you paused the game.
Andre's answer is more easy;
my answer is more accurate.
because getTimer() returns real miliseconds but timer is not ticking exactly accurate.ENTER_FRAME event and setInterval are also same as timer.
that means if you want a more simple code, use Andre's and if you want an accurate Timer, use Mine.
and removing eventListener (3vilguy's answer) is not enough
because getTimer won't Pause !
I hope my answer be useful.
Better using the Timer- Object
var seconds=9;
var t:Timer=new Timer(1000,seconds);
t.addEventListener(TimerEvent.TIMER, updateTimer);
t.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
updateTimer();
t.start();
function updateTimer(e:TimerEvent=null){
var t:uint = t.currentCount;
var dt:uint = seconds - t;
var totseconds:uint = dt;
var minutes:uint = Math.floor(totseconds/60);
var sec:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = sec < 10 ? "0" + sec : sec;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
function timerCompleteHandler(e:TimerEvent):void{
trace("Timer complete");
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
t.stop();
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
t.start();
}
Greetings

Add or remove time from a countdown

I have a timer script:
import flash.utils.Timer;
import flash.events.TimerEvent;
var secs:Number = 30;//second
var mins:Number = 2;//minute
var sec_t:String;
var min_t:String;
var my_timer:Timer = new Timer(1000);
my_timer.addEventListener(TimerEvent.TIMER, timerHandler);
my_timer.start();
showTimer.text = "02:30";
function timerHandler(event:TimerEvent):void
{
if (secs == 0)
{
if (mins == 0)
{
my_timer.stop();
trace("Countdown is finished.");
showTimer.text =String(min_t+sec_t)+" Times Up";
return;
}
else
{
--mins;
secs = 59;
}
}
else
{
--secs;
}
sec_t = (secs < 10) ? "0" + String(secs):String(secs);
min_t = (mins < 10) ? "0" + String(mins) + ":":String(mins) + ":";
trace(min_t+sec_t);
showTimer.text =String(min_t+sec_t);
}
wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
secs = secs - 10;
}
correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
secs = secs + 10;
}
There are two buttons, wrongBtn and correctBtn.
wrongBtn will decrease time by 10 seconds, correctBtn will increase time by adding 10 seconds.
But when the timer second is around 2:05 and I press wrongBtn, the time is displayed incorrectly, like this: "2:0-5". Likewise, when the time is around 2:55 and I press the correctBtn, the time will be displayed as "2:65"...
How can I get this working, so that the output is displayed correctly?
Keep one timer count instead of separate minutes and seconds. You can safely increase and decrease it, and always keep the correct time. To make it readable, just format the output:
import flash.events.TimerEvent;
import flash.utils.Timer;
var timeRemaining:int = 150; // 150 seconds => 2:30 mins
showTime.text = formatTimeRemaining();
var timer : Timer = new Timer (1000);
timer.addEventListener (TimerEvent.TIMER, onTimer);
timer.start();
function onTimer ( ev:TimerEvent ) : void {
timeRemaining--;
if (timeRemaining < 0) {
timeRemaining = 0;
loseGame();
}
else
showTime.text = formatTimeRemaining ();
}
function formatTimeRemaining () : String {
var mins : int = int (timeRemaining / 60);
var minstr : String = mins < 10 ? "0"+mins : ""+mins;
var secs : int = timeRemaining % 60;
var secstr : String = secs < 10 ? "0"+secs : ""+secs;
return minstr+":"+secstr;
}
function loseGame () : void {
timer.stop();
trace("Countdown is finished.");
showTime.text = formatTimeRemaining() + (" Time's Up!");
}
wrongBtn.addEventListener(MouseEvent.CLICK, wrongClick);
function wrongClick(event:MouseEvent):void
{
timeRemaining -= 10;
}
correctBtn.addEventListener(MouseEvent.CLICK, correctClick);
function correctClick(event:MouseEvent):void
{
timeRemaining += 10;
}