DIGITAL CLOCK as3 |
This tutorial is very simple on flash side , but a bit more complex on actionscript side. Since flash Date() variable does not remain double digit number under 10, we will have to add those zeroes under 10 manualy
if we want nice looking digital clock.
At the end we should get something like this :
Open new actionscript 3.0 flash file and insert text field, either use the text tool icon or press T. Size, color, font etc. is all up to you, just make sure the text field is long enought to
display all the digits. Select the text field and make it Dynamic Text and set <Instance Name> to CLOCK
![]() That is all from the stage part of the movie. Now open the actions pannel (press F9) and insert the following actionscript code. function refreshTimes(Event) { // create new date variable var date:Date = new Date(); // variables used to add a 0 to seconds,minutes and hours under 10 var hourZero:String = new String(); var minuteZero:String = new String(); var secondZero:String = new String(); // retreave dates for hours seconds and minutes var h:Number=date.getHours(); var m:Number=date.getMinutes(); var s:Number=date.getSeconds(); // adding 0 to minutes, seconds and hours if under 10 if (s<10) { secondZero="0"; } else { secondZero=""; } if (m<10) { minuteZero="0"; } else { minuteZero=""; } if (h<10) { hourZero="0"; } else { hourZero=""; } // putting all the time variables to one string var displayTime:String = (hourZero +h+":"+minuteZero+m+":"+secondZero+s); // display the time string on the stage CLOCK.text=displayTime; } //run the refreshTimes function every time the frame loads stage.addEventListener(Event.ENTER_FRAME, refreshTimes);
First line is definition of the function we will be calling to refreh the clock every time this frame loads. Lines 5 - 15 creates variables we will be using to display the time.
18 - 43 adds 0 to minutes , hours and seconds if they are under 10, since Date() does not return 0-9 as double digit number with zero. After this if section we will get 01,02,03... instead of just 1,2,3...
Line 46 combines all the date and zero variables to one variables and converts it to string. On line 48 we are sending this string to the CLOCK text field on the stage to display the current time.
Since in actionscript 3.0 Date() does not refresh itself automaticaly like in actionscript 2.0, we have to refresh it manualy by calling this function over and over again every we enter this frame ( 60 times per second by default ).
|