Sort dates in a Flash AS3 DataGrid

旧城冷巷雨未停 提交于 2019-12-13 05:36:38

问题


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.


回答1:


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.




回答2:


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;
        }
    }


来源:https://stackoverflow.com/questions/8892409/sort-dates-in-a-flash-as3-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!