ios - Sorting array based on date and time with two dictionary keys -
i trying sort array based on date , time , can sort array based on date both time coming value in dictionary.
so date comes string in format "yyyy-mm-dd"
, time comes in string in format "hh:mm"
time value comes in key "starts"
string '"hh:mm"' format.
i know somehow need combine 2 strings 'yyyy-mm-dd hh:mm'
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 solve problem?
you need sort times well, why sortusingdescriptors:
takes 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; }
Comments
Post a Comment