Reputation: 277
This has been driving me crazy, I need to sort a Flash DataGrid column (not Flex) by date. I have tried giving the date column a sort function like below:
colTwo.sortCompareFunction = sortDate;
and this is the function:
private function sortDate ($obj1,$obj2) : int {
trace("created date in sort "+$obj1["created"]);
var t1:Array = $obj1["created"].toString().split("-");
var t2:Array = $obj2["created"].toString().split("-");
var t1dt:Number=(new Date(Number(t1[0]),Number(t1[1]),Number(t1[2]))).getTime();
var t2dt:Number=(new Date(Number(t2[0]),Number(t2[1]),Number(t2[2]))).getTime();
trace(t1dt);
if(t1dt < t2dt) {
return -1;
} else if(t1dt == t2dt) {
return 0;
} else {
return 1;
}
}
But this still seems to attempt to sort the column alphabetically.
Any help would be appreciated.
Upvotes: 0
Views: 1421
Reputation:
The answer by redHouse71 is OK, because it would give you a correct result, but as a code example... well, below is another variant, which does essentially the same thing, but is less wordy.
private function sortDate(a:Object, b:Object):int
{
var difference:Number =
this.truncateDate(a) - this.truncateDate(b);
return difference / Math.abs(difference);
}
// replace Object with the proper type
private function truncateDate(object:Object):uint
{
return (object.created as Date).time * 0.0001;
}
EDIT: but why do you have to truncate the date to seconds? Also, it's not necessary to return strictly -1, 0, 1, basically you could do away with just this.truncateDate(a) - this.truncateDate(b)
- I added the "rounding" to make it behave as the original answer.
Upvotes: 1
Reputation: 277
As mentioned in the comments, converting to unix timestamp works:
public function sortDate ($obj1,$obj2) : int {
var dateOne:Date = $obj1["created"];
var epoch:Number = Math.round(dateOne.valueOf()/1000);
var dateTwo:Date = $obj2["created"];;
var epochTwo:Number = Math.round(dateTwo.valueOf()/1000);
var t1dt:Number = epoch;
var t2dt:Number = epochTwo;
if(t1dt < t2dt) {
return -1;
} else if(t1dt == t2dt) {
return 0;
} else {
return 1;
}
}
Upvotes: 0