Displaying Date and Time in Flash AS3

Published on Monday, November 9th, 2009 by Matthew Alberty

I’ve recently been working on a simple digital signage demo and one of the components required the current date and time to be displayed. I am developing this module in Adobe Flash ActionScript 3 and thought I could save some time by searching the web for a standard solution. Surprisingly, I was not able to find a workable solution that included the fix for single digit minutes, such as 12:01. Instead, all scripts displayed 12:1.

I have provided the full working code below to fix this issue. This code will display the current date and time in this format: November 19, 2009 | 1:15 pm

//start AS3 code

var my_date:Date;

var my_timer:Timer=new Timer(1000);
my_timer.addEventListener(TimerEvent.TIMER, onTimer);
my_timer.start();

var months:Array = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

function onTimer(e:TimerEvent):void {
my_date = new Date();

var theHours = my_date.hours;
var theMinutes = my_date.minutes;
var ampm;

//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 < 10) {
theMinutes=”0″+theMinutes;
}

time_txt.text = months[my_date.month] + ” ” + my_date.date + “, ” + my_date.fullYear + ” | ” + theHours + “:” + theMinutes + ” ” + ampm;
}

//end AS3 code

Leave a Reply

  1. * Indicates a required field.

    Powered by WP Hashcash