Flash Date Errors

Flash has a lot of functions for creating and setting dates but you have to be careful using them. In fact it may be safer not to use them at all.

Consider this action script:

view plain print about
1var birthdate:Date = new Date();
Will this always set the date to be 17th July 1969?

What about this code?

view plain print about
1var birthdate:Date = new Date();
Will this always set the date to be 31th March 1969?

Answer is in the with the first date the date will always be correct, but with the second it will not be correct all of the time and even worse if it's correct will depend on what the current date is.

The issue is that new Date() sets the date to be the current date and setDay does a little more than you expect. If today was a month that had less than 31 days the brithdate would be set to the 1st, 2nd or 3rd of March (depending on the days in the month) not the 31st of March!

The setDay method acts as if it's adding a number of days to the start of the Month rather than setting the day of the Month. If the number of days exceed the number of days in the month it rolls the date over into the next month.

Here's some code to show this:

view plain print about
1// Set day to 31 March
var birthdate:Date = new Date(1969,1,1,0,0,0,0); // date in Feb 1969
The output is:
view plain print about
1Mon Mar 3 12:00:00 GMT+1000 1969

Some Americans reading this might be asking why would you set the date first rather than the month? Here in Australia (and also in Europe) dates are written with the date first not the month first, so it would be not unusual to see code written like this.

So what if you set the month first ie call setMonth before setData?

In this case it does fix this issue. However you can still run into issues with other code involving dates because when you set the month the number of days are truncated if they exceed the number the month has.

The safest thing to do is to avoid the setMonth and setDay date methods and just set dates via the date constructor.

view plain print about
1var birthdate:Date = new Date(1969,6,17,0,0,0,0);

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)