Date objects don’t have a built-in compare() method, but comparing dates is still pretty easy.
The key is to not even look at the Date objects themselves, but rather the values represented by the objects using the Date.getTime() method:
Returns the number of milliseconds since midnight January 1, 1970, universal time, for a Date object. Use this method to represent a specific instant in time when comparing two or more Date objects.
This makes comparing dates as trivial as comparing numbers.
Here’s a simple method that compares two dates, returning -1 if the first date is before the second, 0 if the dates are equal, or 1 if the first date is after the second:
|
public function compare (date1 : Date, date2 : Date) : Number { var date1Timestamp : Number = date1.getTime (); var date2Timestamp : Number = date2.getTime (); var result : Number = -1; if (date1Timestamp == date2Timestamp) { result = 0; } else if (date1Timestamp > date2Timestamp) { result = 1; } return result; } |

5 comments
Comments feed for this article
January 26, 2009 at 3:03 pm
higbeem
Thanks for the posting. I’m new to flex/actionscript and I didn’t understand why comparing dates as Dates wasn’t working.
January 26, 2009 at 3:36 pm
Nick Schneble
No problem! Glad I could help.
January 29, 2009 at 11:50 am
eggplant
ObjectUtil.dateCompare( date1, date2);
There’s even stringCompare and numericCompare. I used to do what you did for so long until I discovered these built-in functions. They’ve been in there since at least Flex Beta 3 (the oldest docs I have lying around that I could find).
January 29, 2009 at 2:15 pm
Nick Schneble
@eggplant
Yeah, ObjectUtil is great for comparisons. I tend to do date comparisons using milliseconds more often because I’m usually interested not only in the order of the dates, but in the difference between them as well.
The compare() method above could easily be modded to return the difference instead of -1, 0 or 1. Otherwise you’re right, ObjectUtil.dateCompare() does exactly the same thing.
February 6, 2009 at 8:27 am
Flexing » Blog Archive » Date Comparison Object
[...] Flex 3 (ActionScript 3) does not have a date compare function I used google and found this post: http://userflex.wordpress.com/2008/09/11/as3-date-compare/. It is a great function and seems to work just [...]