使用两个字典键基于日期和时间对数组进行排序

时间:2013-08-12 20:07:58

标签: ios objective-c sorting nsdate

我正在尝试根据日期和时间对数组进行排序,我可以根据日期成功对数组进行排序,这两个时间都将作为字典中的另一个值。

所以日期是"yyyy-MM-dd"格式的字符串,时间是格式为"HH:mm"的字符串

时间值以键"starts"的形式出现在字符串'“HH:mm”'格式中。

我知道我需要将两个字符串组合到'yyyy-MM-dd HH:mm'但是如何?

-(NSMutableArray *)sortArrayBasedOndate:(NSMutableArray *)arraytoSort
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSComparator compareDates = ^(id string1, id string2)
    {
        NSDate *date1 = [formatter dateFromString:string1];
        NSDate *date2 = [formatter dateFromString:string2];

        return [date1 compare:date2];
    };


    NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"start_date" ascending:YES comparator:compareDates];
    [arraytoSort sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];


    return arraytoSort;
}

知道如何解决这个问题?

2 个答案:

答案 0 :(得分:9)

您还需要对时间进行排序,这就是sortUsingDescriptors:采用数组的原因。

-(NSMutableArray *)sortArrayBasedOndate:(NSMutableArray *)arraytoSort
{
    NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init];
    [fmtDate setDateFormat:@"yyyy-MM-dd"];

    NSDateFormatter *fmtTime = [[NSDateFormatter alloc] init];
    [fmtTime setDateFormat:@"HH:mm"];

    NSComparator compareDates = ^(id string1, id string2)
    {
        NSDate *date1 = [fmtDate dateFromString:string1];
        NSDate *date2 = [fmtDate dateFromString:string2];

        return [date1 compare:date2];
    };

    NSComparator compareTimes = ^(id string1, id string2)
    {
        NSDate *time1 = [fmtTime dateFromString:string1];
        NSDate *time2 = [fmtTime dateFromString:string2];

        return [time1 compare:time2];
    };

    NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"start_date" ascending:YES comparator:compareDates];
    NSSortDescriptor * sortDesc2 = [NSSortDescriptor sortDescriptorWithKey:@"starts" ascending:YES comparator:compareTimes];
    [arraytoSort sortUsingDescriptors:@[sortDesc1, sortDesc2]];

    return arraytoSort;
}

答案 1 :(得分:0)

将两者连接到一个时间戳。然后从参考日期开始获取TimeInterVal, 并按此号码排序