I am building a quiz and i need to calculate the total time taken to do the quiz. and i need to display the time taken in HH::MM::SS..any pointers?
new Date().time returns the time in milliseconds.
var nStart:Number = new Date().time;
// Some time passes
var nMillisElapsed:Number = new Date().time - nStart;
var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" +
(Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" +
(Math.floor(nMillisElapsed / (1000)) % 60);
I resurrect this question to say that both Brian and mica are wrong. Creating a new Date() gives you the time according to the computer's clock. All someone has to do is set their clock back several minutes, and that would cause the quiz timer to go back several minutes as well. Or worse, they could set their clock back to a time before they started the quiz, and your app would think they spent a negative amount of time taking the quiz. o.O
The solution is to use flash.utils.getTimer(). It returns the number of milliseconds since the swf started playing, regardless of what the computer's clock says.
Here's an example:
var startTime:Number = getTimer();
// then after some time passes:
var elapsedMilliseconds:Number = getTimer() - startTime;
Then you can use Brian's code to format the time for display:
var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + "::" +
(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + "::" +
(Math.floor(elapsedMilliseconds / (1000)) % 60);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With