So we have for example two DateField inputs in our Flex application, and we want to calculate the difference in days between the two. Below is the application that does just that. The difference is shown in the Label below the two DateFields (Sorry that you have to navigate to different site, but wordpress.com wont allow me to embed flash).

Click to Launch application – hosted on my webstite tdteam.com

First let’s take a look at the function that does all of the work.

private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}

Function differenceBetweenDates takes in two arguments – date1 and date2 and both are of type Date. Function also returns a value – in our case a Number that indicates the number of days between two dates. First we assign number of miliseconds in a day to variable MS_PER_DAY (1 day in seconds = 60 (sec) * 60 (min) * 24 (hr), if we multiply this number by 1000 we get result in miliseconds).

Then we assign difference between two dates to a variable tempDate. Next we just have to divide the tempDate (which holds the difference in dates) in miliseconds, with tempDate.time with MS_PER_DAY.

We than round off the result with Math.round and since we want a positive value out of our function we apply Math.abs. (in case date1 would be greater than date2, we would get a negative number in the difference variable, since we used Math.abs that will not happen).

On the last line we just return the value that was assigned to the variable difference.

Below is the code of the whole Flex application. We must just mention that when ever a user changes either date1 or date2 we call the change() function, which calculates new difference (with the function differenceBetweenDates) and displays the result in Label with id diff. We also added the initialize=”change()” in the mx:application tag, which triggers the function change() when the application is initialized – that way we get the result right away when application loads.

Source code of Flex application that calculates the difference between two dates

### Like this:

Like Loading...

*Related*