Creating a clock in Actionscript 3.0 with the Date class.
January 2nd, 2009
After seeing a recent application, for some reason recently created and built in AS2!!?? I thought it would be great to create a similar application in AS3 to show how simple, effective and great this would be.
As you can see from the code, I have created an instance of theĀ Date class to ascertain the current date for the date display at the bottom of the swf , this is also called upon on completion of the timer event, which is called every second and updates the state of the clock face.
To get the days and months of the date display, as flash assigns numbers to these elements, 0-6 for the days and 0-11 for the months etc, this runs in well with the Array elements so an array is created and then referenced to in the call to this on creating the text.
-
private function init(e:Event)
-
{
-
var currentTime:Date = new Date();
-
var month:Array = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
-
var dayOfWeek:Array = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
-
-
date_text.text = dayOfWeek[currentTime.getDay()] + " " + currentTime.getDate() + " " + month[currentTime.getMonth()] + " " + currentTime.getFullYear();
Note that I have chosen the Timer calss to use for keeping the time updated rather that an Enter_Frame event, the reason for this is that the timer class runs at the specified time (every second in this case) rather than at the frame rate of the swf which can slow down depending on the users cpu, which could slow the time on the clock down, this would also run at a certain times per second (the frame rate of the swf) resulting in too many checks, when really, only one a second would suffice, so this method would result in a more accurate looking and better running clock.
The date class has to be called upon each second to update the time, as if this is created before the function as called the time stays the same. This seems to be the best method I could find as the Date class doesn't seem to have an update() method, if somebody else finds a better work around please do feel free to let me know.
-
private function timeListener(e:Event):void
-
{
-
-
var currentTime:Date = new Date();
-
var minutes = currentTime.getMinutes();
-
var seconds = currentTime.getSeconds();
-
var hours = currentTime.getHours() * 30 + currentTime.getMinutes() / 2;
-
seconds_hand.rotation = seconds * 6;
-
minutes_hand.rotation = minutes * 6;
-
hours_hand.rotation = hours;
-
}
Just to add a bit of fun to the clock I have made the colour changeable and the clock draggable through the centre of the face.
Have fun!
Get the source here.
Categories: Actionscript 3.0, Tutorials | Tags: Actionscript 3.0, AS3, Date class | 24 Comments


![Validate my RSS feed [Valid RSS]](http://www.ultravisual.co.uk/blog/images/valid-rss.png)




