Display time in Actionscript 3

Posted on October 3, 2009. Filed under: Tutorials |

In this tutorial you will learn how to display the time in Actionscript 3.0. This is an update from the previous AS2 version. The code in this tutorial is very similar to the previous version, only minor adjustments are needed. Displaying the time uses the Date class which represents the time and date information. I have created this tutorial in Flash CS4, but it should work fine in CS3.

Step 1

Open a new Flash AS3 file.
Select the text tool with dynamic text and drag a dynamic text field on the stage as shown below:

Select the dynamic text field then choose the ‘Character Embedding’ and select Lowercase, Numerals and Punctuation.

Step 2

Give your dynamic text field the instance name ‘theTime’ like below:

Step 3

On the timeline create a new layer called ‘Actions’. Then select the first frame and hit F9 to open up the actions panel and enter the following code:

//Adds the enter frame event to the dynamic text field.
theTime.addEventListener(Event.ENTER_FRAME,showTime);

function showTime(event:Event):void {
   //Create a new instance of the date class.
   var myTime:Date = new Date();
   //This returns the seconds, minutes and the hour.
   var theSeconds=myTime.getSeconds();
   var theMinutes=myTime.getMinutes();
   var theHours=myTime.getHours();
   var ampm:String;

   //Displays am/pm depending on the current hour.
   if (theHours>=12) {
        ampm="pm";
   } else {
        ampm="am";
   }
   //This subtracts 12 from the hour when it greater than 13.
   if (theHours>=13) {
       theHours=theHours-12;
   }
   if (theMinutes == 1) {
       theMinutes="0"+theMinutes;
   }
   if (theSeconds ==1) {
       theSeconds="0"+theSeconds;
   }
   //Displays the time in the dynamic text field.
   theTime.text =theHours+":"+theMinutes+":"+theSeconds+" "+ampm;
}

Step 4

Test the movie clip Ctrl + Enter. You should now have a time display in Actionscript 3.0.

Advertisement

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.