Sunday, August 14, 2011

Flash / Flex AS3: Finding the difference between 2 dates

I have encounter numerous situation where there is a need to compare 2 different dates. I have created a simple example to demonstrate how to find out the difference between 2 dates.



	
		Days: " + tempArray[0] + "";
				outputTxt.htmlText += "
Hours: " + tempArray[1] + ""; outputTxt.htmlText += "
Minutes: " + tempArray[2] + ""; outputTxt.htmlText += "
Seconds: " + tempArray[3] + ""; outputTxt.htmlText += "
MilliSeconds: " + tempArray[4] + ""; } ]]>

package
{
	import mx.controls.DateField;
	import mx.controls.TextArea;

	public class TimeDifferenceMain
	{
		public function TimeDifferenceMain()
		{
		}
		
		public function compareDate(tempDate:Date):Array
		{
			//2 dates object: 1 is today's date, the other 1
			//is the selected date
			var now:Date = new Date();
			var selectedDate:Date = tempDate;
			
			//to store the difference of both dates in numerical value
			var remainder:Number;	
			
			//Store the number of milliseconds of both date since 1970
			var nowNum:Number = now.getTime();
			var selectedDateNum:Number = selectedDate.getTime();
			
			//Numbers to store number of milliseconds in eash day, 
			//each hour, each minute and each second
			var dayValue:Number = 24 * 60 * 60 * 1000;
			var hrValue:Number = 60 * 60 * 1000;
			var minValue:Number = 60 * 1000;
			var secValue:Number = 1000;
			
			//Compare which date is bigger and find the difference
			if(nowNum > selectedDateNum)
			{
				remainder = nowNum - selectedDateNum;	
			}else{
				remainder = selectedDateNum - nowNum;
			}
			
			//Modulas play a big role here as it is used to find
			//out the remainder of the next smaller unit
			var hrLeft:int = remainder % dayValue;
			dayValue = (remainder - hrLeft)/dayValue;
			var minLeft:int = hrLeft % hrValue;
			hrValue = (hrLeft - minLeft)/hrValue;
			var secLeft:int = minLeft % minValue;
			minValue = (minLeft - secLeft)/minValue;
			var milliSecLeft:int = secLeft % secValue;
			secValue = (secLeft - milliSecLeft)/secValue;
			
			//Create a array and store the output into the array
			var resultArray:Array = new Array();
			resultArray.push(dayValue);
			resultArray.push(hrValue);
			resultArray.push(minValue);
			resultArray.push(secValue);
			resultArray.push(milliSecLeft);
			return resultArray;
		}
	}
}

Click here to view the demo.
Click here to download the source file of the demo.

No comments:

Post a Comment