views:

310

answers:

5

The intention of this question is to gather solutions to date / time calculation using the built in Date class instead of writing long complicated functions.

I’ll write some answers myself, and accept an answer if anyone comes up with something very clever. But this is mostly meant as a collection of solutions, since I often see overly complicated code for handling dates.

Please remember this is not for long solutions for things the Date class can not do.

A good place to start is the reference found here: http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Date.html

A: 

To get the current system date simply create a new Date object without passing any values to the constructor. Like this:

var today:Date = new Date();
trace("The date and time right now is: " + today. toLocaleString());
trace("The date right now is: " + today. toLocaleDateString());
trace("The time right now is: " + today. toLocaleTimeString());
Lillemanden
A: 

To properly compare to dates you need to use the getTime() function, it will give you the time in milliseconds since January 1, 1970. Which makes it easy to compare to dates, a later date will return a larger value.

You can subtract one from the other to get the difference, but unfortunately there is no built in time span class to handle this cleanly; you will have to use a bit of math to present the difference properly to the user (eg. dividing the difference with the number milliseconds in a day to get the difference in days).

var date1:Date = new Date(1994, 12, 24);
var date2:Date = new Date(1991, 1, 3);
if(date1.getTime() > date2.getTime())
    trace("date1 is after date2");
else
    trace("date2 is after or the same as date1");
Lillemanden
A: 

The built in Date class handles “overflow” very well, this can be used to add or subtract time. If one of the fields overflows, the date class handles it by adding or subtracting the overflow.

var date:Date = new Date(1993, 12, 28);
trace("7 days after the " + date.toLocaleDateString());
date.setDate(date.Date + 7);
trace("It was the " + date.toLocaleDateString());
Lillemanden
A: 

You can easily find out if a year was a leap year without coding all the exceptions to the rule by using the Date class. By subtracting one day from marts the 1st (requesting marts the 0th), you can find the number of days in February.

Remember that month is zero-indexed so Marts being the 3rd month has index 2.

function CheckIfYearIsLeapYear(year:uint):Boolean
{
    return new Date(year, 2, 0).Date == 29;
}
Lillemanden
+1  A: 

There's also ObjectUtil.dateCompare(a,b)

anon