Thursday, 12 April 2012

How to get the REAL date into Flash

Flash has a Date object, that can give you the date and time, but it gives you the date and time that is on the users computer.

e.g.
var dt:Date = new Date();
trace(dt);

This will trace out whatever time the user's computer is set to, whether it is 5mins slow, or 10 years fast.

If this date/time is being used for some kind of authentication i.e. to see if the deadline is past, then you should load the time from the server.

var ld:LoadVars = new LoadVars();
ld.onLoad = function(succ:Boolean) {
        dt_txt.text = this.servertime;
}
ld.sendAndLoad('servertime.php',ld,'POST');

On the servertime.php file:


$today = date('YmdHis');
echo "&servertime=$today";
?>

(Sometimes I have issues with the data being echoed out, try removing the ampersand from the front, or not.)

The reason why I use the date('YmdHis') is because it gives you a number that is perfect for sorting, and a recognised datetime stamp for mysql, if you ever need it.

4.30pm (and 22 seconds), 5/11/2012   =    20121105163022

If you need to sort the dates, you can do a numeric sort. If you want to check if something happened before Jun 2012, you look to see if the number is smaller than 20120600000000, and so on.

No comments:

Post a Comment

Please enter your message here...