Sorting array based on date and time with two dictionary keys

谁说我不能喝 提交于 2019-12-06 12:51:32

问题


I am trying to sort an array based on date and time , I can successfully sort the array based on date both time is coming as another value in dictionary.

So date comes as a string in format "yyyy-MM-dd" and time comes in as a string in format "HH:mm"

Time value comes in key "starts" as string '"HH:mm"' format.

I know somehow I need to combine two strings to 'yyyy-MM-dd HH:mm' but how?

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

Any idea how can I solve this problem?


回答1:


You need to sort the times as well, that is why sortUsingDescriptors: takes an array.

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



回答2:


Concatenate both to one timestamp. Then get the TimeInterVal since ref date, and sort by this number



来源:https://stackoverflow.com/questions/18195774/sorting-array-based-on-date-and-time-with-two-dictionary-keys

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