Flash for the masses – AS, JSFL, XUL, etc.

2008/12/30

Offset timer alarm based on UTC or local time

Filed under: AS3.0 — delfeld @ 9:27 pm
Tags: , , , ,

This is from my response to a post on finding UTC time from a local time on ActionScript.org

Simply add the Date object’s getTimezoneOffset() (this is in minutes) to the resulting time offset.

With AS3, it is easy to make this into a class, and inherit that class from a Flash library object’s “linkage”.

The class below is not very robust, since there is only a single alarm per class instance, and no error-checking. However, it does show how to convert to UTC time.

package
{
	import flash.display.MovieClip;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * ...
	 * @author Delfeld, copyright 2008
	 */
	public class alarmTestAS extends MovieClip
	{
		private var alarm:Timer;
		private var endingDate:Date;

		public function alarmTestAS()
		{
			getAlarmDate(0, 0, 0, 2, true);
			setAlarm();
		}

		private function setAlarm():void
		{
			// end time - immediate time = offset time, timer delay, timer interval, etc.
			alarm = new Timer(endingDate.time - (new Date()).time,1);
			alarm.addEventListener(TimerEvent.TIMER_COMPLETE, timerHandler, false, 0, true);
			alarm.start();
		}

		private function getAlarmDate(dyOffset:int, hrOffset:int, mnOffset:int, secOffset:int, asUTC:Boolean = false):void
		{
			endingDate = new Date();
			//endingDate.setMinutes(endingDate.minutes + endingDate.timezoneOffset);

			// Change time to an offset of the current UTC time.
			// Note that this will still maintain your current clock's offset in the endingDate object,
			// but the time - delivered via a non-UTC method - will be offset from the UTC time.
			if (asUTC)
			{
				trace(" UTC offset minutes: " + endingDate.timezoneOffset);
				endingDate.setUTCHours(
					endingDate.getUTCHours() + hrOffset,
					endingDate.getUTCMinutes() + mnOffset + endingDate.getTimezoneOffset(),
					endingDate.getUTCSeconds() + secOffset
				);
				endingDate.setUTCDate(
					endingDate.getUTCDate() + dyOffset
				);
			}
			// Change time to an offset of the current local time.
			else
			{
				endingDate.setHours(
					endingDate.getHours() + hrOffset,
					endingDate.getMinutes() + mnOffset, //+ endingDate.getTimezoneOffset()
					endingDate.getSeconds() + secOffset
				);
				endingDate.setDate(
					endingDate.getDate() + dyOffset
				);
			}

			trace(" alarm time: \t" + endingDate.toString());
			trace(" local time: \t" + (new Date()).toString());
			trace(" UTC time: \t\t" + (new Date()).toUTCString());
		}		

		private function timerHandler(e:TimerEvent):void
		{
			alarm.stop();
			e.target.removeEventListener(e.type, timerHandler);
			trace("alarmTestAS.timerHandler: " + alarm.delay + " ms");
		}
	}
}

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.