When 2 – 1 = 2 when doing math operations with dates in ActionScript

September 4th, 2011

Let’s say we have the following use-case: we have to create a calendar with Month view. The Month view can start on any day, it can be 1st of March, it can be 15th of March, it can be even 31th of March.

So, assume that our current date range starts with 31th of March. And now, what if we want to scroll the date back one month? Hah,easy, you would jump immediately with straightforward solution, just subtract 1 month from current Date.

Writing a few lines of code, doing some traces.

var startDate : Date = new Date (2011, 2, 31);
var newDate : Date = new Date (startDate.time); //displays Thu Mar 31 2011
 
trace ("startDate=", startDate.toDateString()); 
newDate.month--;		
 
trace ("newDate=", newDate.toDateString()); //displays Thu Mar 3 2011

..and wait a minute, how it is possible that 2 – 1 = 2 for new month value?

Well, the issue is that Flash Player behind the scene is fixing invalid resulting date for February month. We could not have February date with 31 days, so somebody has to do something about it, right?

To sum up we should remember about this feature of Flash Player when dealing with invalid dates and the correct operation for subtracting 1 month from existing date can be the following:

var startDate : Date = new Date (2011, 2, 31);
var initNewDate : Date = new Date(startDate.time)
var newDate : Date;
 
initNewDate.month--;				
newDate = handleShorterMonths(startDate, initNewDate, 1);
trace ("newDate=", newDate.toDateString()); //displays Mon Feb 28 2011
 
private function handleShorterMonths(startDate : Date, dateToCheck :Date, monthIndex : int) : Date {
   var correctDate : Date = dateToCheck;
   if (dateToCheck.date < startDate.date) {
        correctDate.date = startDate.date - dateToCheck.date;	
	correctDate.month = monthIndex;
   }
   return correctDate; 
}

Interactive sample with view source enabled that illustrates the issue:

Get Adobe Flash player

Alternatively, if you do not like to do Date Math operations by yourself, you can always rely on As3Commons DateUtils.as class.

This utility class has a very well written API to do various Math operations with Dates – you add days, months, years, etc. to existing date with an ease.

  • ?????? ??????

    this post is (-?_?) dated!

    • jabbypanda

      Can you elaborate a little bit more on your response?

      As long as this article is directly linked from official Adobe livedocs, I think more people can benefit from the information that you know and I do not know yet.

  • Phil

    View source yields a 404 error :(