Search Flex Components Free

Custom Search

December 10, 2007

Handling Time in Flash

Working with time can be very frustrating. Here are some pointers that simplify working with time in Flash allowing you to work effectively with GMT.&

1. Use date and time as a GMT number and use the Date Object for conversion.

Why? Working with Date objects can be frustrating and most of the time, using a numerical equivalent is much easier and much cleaner especially when adding and subtracting time.

currentGMT = new Date().getTime()
trace(currentGMT) // 1096649692484 or Fri Oct 1 12:54:52 GMT-0400 2004

The value 1096649692484 is the milliseconds from Jan 1, 1970 in universal time according to your system time and time zone. Universal time or Zulu Time or Greenwich Mean Time(GMT) is the time at the Royal Greenwich Observatory near London, England. When working within the Date Object, internally it works with GMT and adjusts the output for your local time zone. All values returned from a date object include adjustments for the local time zone, where the getTime value is the real GMT value in Milliseconds from 1970. This value is time zone distortion free.

Subtract 2 hours from Fri Oct 1 12:54:52 GMT-0400 2004:

How many Millseconds in 1 hour from Google Calculator

trace( new Date( new Date( 1096649692484 ) - new Date( 3600000 * 2)) )

or

trace( new Date( 1096649692484 - 3600000 * 2 ))

Date objects are converted to a GMT number before math operations. When you get a number as a result of adding 2 date objects, the result is always GMT milliseconds. If your not prepared for this it will throw you for a loop.

2. Always store time and date as GMT.

GMT allows you to localize time in your applications. If you store time as a combination of date, hour, minutes, seconds and millisecond, you will have neglected the time zone. This is especially important when you store values into a database where users will be viewing data based on times entered. If the application adding times into the database is entering local time, each value is distorted according to the values of the time zone where the data was entered. It is ideal to make time comparable so if a user is in Guong Zho, China or in San Francisco the times will be comparable even though the users are on wildly different time zones. GMT allows everyone to speak the same time language.

3. Convert GMT to Date within Date constructor

The Date object in Flash supports a constructor argument allowing you to create a Date object set to a GMT time zone instantly.

myTime = new Date (1096649692484)
trace(myTime) //Fri Oct 1 12:54:52 GMT-0400 2004

Next time you do a project involving time, remember GMT is your friend.

Related Flex Tutorials