0

I have an ArrayCollection that I'd like to sort by date and then time (in case there's two items with the same date). I've got it sorting by date fine (YYYY/MM/DD) but I can't figure out the time bit, time is in 24 hour format so the code would be basically the same as for the date.

This is the code I used for the date sorting, it works fine.

import mx.collections.SortField;
import mx.collections.Sort;

private function sort():void  
{
var dataSortField:SortField = new SortField();
dataSortField.name = "date";

var arrayDataSort:Sort = new Sort();
arrayDataSort.fields = [dataSortField];

reminderXMLArray.sort = arrayDataSort;
reminderXMLArray.refresh();
}
user1584282
  • 3
  • 1
  • 4
  • Are the date and time two separate fields? Or are they in the same field? If the same field, I'm surprised what you're doing isn't working. You may have to go to a SortCompareFunction. – JeffryHouser Sep 13 '12 at 02:27
  • In that case; you need to use a sortCompare function. Looks like Ivan provided more details in a formal answer. – JeffryHouser Sep 13 '12 at 12:25
  • I made a class and added the time on the end of the date so it searches like 2012/10/31PM0100, that's year/month/day/AM or PM/hour/minute, handy that A is before P in the alphabet! It goes into a datagrid with the column set to visible="false" and a nice date with the day of the week visible like - Wed Oct 31 2012 12:00 PM. Thanks for the advice both of you. – user1584282 Sep 14 '12 at 03:28

2 Answers2

2

You can use this code to sort by date and time:

private function sort():void
{
    var dataSortField:SortField = new SortField();
    dataSortField.name = "date";
    dataSortField.compareFunction = function (a:Object, b:Object) : int {
        var na:Number = a.date.getTime();
        var nb:Number = b.date.getTime();

        if (na < nb)
            return -1;

        if (na > nb)
            return 1;

        return 0;
    };

    var arrayDataSort:Sort = new Sort();
    arrayDataSort.fields = [dataSortField];

    reminderXMLArray.sort = arrayDataSort;
    reminderXMLArray.refresh();
}
Ivan Dyachenko
  • 1,348
  • 9
  • 16
0

As there are two separate fields that you want to sort on you can just use the Sort object's fields Array to add two sort fields:

var sort:Sort = new Sort();
var fields:Array = [ new SortField("date"), new SortField("time") ];
sort.fields = sort;
dannrob
  • 1,061
  • 9
  • 10