How to sort Dates in objective C? - ios

In my app I am bookmarking the words in different days, I have the sorting options such as sort recent first and oldest first. I am unable to sort the words according to the bookmarked date, How to do it? By using Descriptors my sorting is not fine as only the first two entries are getting sorted. My code is:
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:#"cellType" ascending:NO selector:#selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:#"entrydate" ascending:NO selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil];
[self.favoriteEntries sortUsingDescriptors:sortDescriptors];
[[NSUserDefaults standardUserDefaults] setValue:#"descendingDate" forKey:#"BookmarkSortType"];

You can use bubble sort.It will give you exact result without any confusion.Yes , the line of codes are more than predefined function but it will be correct to use bubble sort.

Try like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];//SET_YOUR_DATE_FORMAT
NSString *updatedDateStr1 = YOUR_FIRST_DATE_STRING;
NSDate *date1 = [dateFormatter dateFromString:updatedDateStr1];
NSString *updatedDateStr2 = YOUR_SECOND_DATE_STRING;
NSDate *date2 = [dateFormatter dateFromString:updatedDateStr2];
NSComparisonResult result = [date2 compare:date1];//THIS WILL RETURN ONE OF NSOrderedAscending , NSOrderedSame, NSOrderedDescending

Looks like you have NSString Object. you need to convert it in NSDate object then compare using Predicate and sort as per your need. Modify obj whatever you have in your dictionary or array.
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];// Whatever your current stringDate format.
[df setTimeZone:[NSTimeZone systemTimeZone]];
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
NSDate *dd = [df dateFromString:(NSString *)obj ];
return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];
NSArray *arrFutureDates = [yourArray filteredArrayUsingPredicate: findFutureDates];
NSLog(#"%#",arrFutureDates);
Maybe this will help you.

Related

how to sort array of dates in ascending order in ios

I have a NSMutableArray that contains dates in string format. Here I need to sort that array in order of ascending order of dates. I used strong text
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
But it only sort the dates in terms of ascending order of day and month. Year is not considered. Please help me.
For example, Array contains
03/09/2017, 03/06/2016, 01/06/2016,01/04/2016 and 03/01/2017.
After using the above lines of code, Array contains like,
01/04/2018, 01/06/2016, 03/01/2017, 03/06/2016, 03/09/2016
You need to use sortedArrayUsingComparator like this way to sort date with String array.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSDate *d1 = [df dateFromString: obj1];
NSDate *d2 = [df dateFromString: obj2];
return [d1 compare: d2];
}];
Note : Set formate of date According to your date, it is hard to predicate date formate from your example thats why I have used MM/dd/yyyy, if your date contain formate dd/MM/yyyy then use that.
your code is correct but date format wrong.
try this code:
NSMutableArray *dateArray = [[NSMutableArray alloc] initWithArray: #[#"03/09/2017", #"03/06/2016", #"01/06/2016",#"01/04/2016", #"03/01/2017"]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date;
for (int i = 0; i < dateArray.count; i++) {
[formatter setDateFormat:#"MM/dd/yyyy"]; // Please your date format set.
date = [formatter dateFromString:[dateArray objectAtIndex:i]];
[formatter setDateFormat:#"yyyy/MM/dd"];
[dateArray replaceObjectAtIndex:i withObject:[formatter stringFromDate:date]];
}
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Array: %#",reverseOrder);
Please try below code:
NSArray *strDateArray = [[NSArray alloc] initWithObjects:#"03/09/2017",#"03/06/2016", #"01/06/2016",#"01/04/2016",#"03/01/2017", nil];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSMutableArray *dateArray = [[NSMutableArray alloc] init];
for (NSString *dateString in strDateArray) {
NSDate *date = [formatter dateFromString:dateString];
[dateArray addObject:date];
}
// sort array of dates
[dateArray sortUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
// return date1 compare date2 for ascending. And reverse the call for ascending.
return [date1 compare:date2];
}];
NSLog(#"dateArray %#", dateArray);
NSMutableArray *sortedDateArray = [[NSMutableArray alloc] init];
for (NSDate *date in dateArray) {
NSString *dateString = [formatter stringFromDate:date];
[sortedDateArray addObject:dateString];
}
NSLog(#"sortedDateArray %#", sortedDateArray);
For Swift 4.0
let formater = DateFormatter()
formater.dateFormat = "MM/dd/yyyy" //date formate should be according to your date formate
let sortedArray=arrayToSort.sorted(){
(obj1, obj2) in
let date1=formater.date(from: obj1)
let date2=formater.date(from: obj2)
return date1!<date2!
}
//You can change the date format according to your code
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSArray *sortedArray = [YourArraysortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2)
{
NSString *strDateObj1 = [NSString stringWithFormat:#"%#",[obj1 valueForKey:#"BirthDate"]];
NSString *strDateObj2 = [NSString stringWithFormat:#"%#",[obj2 valueForKey:#"BirthDate"]];
NSDate *d1 = [df dateFromString: strDateObj1];
NSDate *d2 = [df dateFromString: strDateObj2];
return [d1 compare: d2];
}];
NSLog(#"%#", sortedArray)

Sort objects based on a NSString date

I have an array of objects which all contain a expectedDeliveryDate string. I have a method which takes a date string and turns it into a NSDate.
How can I sort these in ascending or descending order?
I am assuming that you have an Array in which each object is Dictionary and it contains data of delivery
try this I create this method in my project to sort array with Key.
In this method lastDescriptor has selector compare: so two date will compare and sort automatically in this method.
-(NSMutableArray *)sortArrayWithKey:(NSString *)sortingKey andArray:(NSMutableArray *)unsortedArray{
NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:sortingKey ascending:NO selector:#selector(compare:)];
NSArray *descriptors = [NSArray arrayWithObjects: lastDescriptor, nil];
return [unsortedArray sortedArrayUsingDescriptors:descriptors].mutableCopy;
}
Hope this help you too..
Sorting the array with NSString date.
Things Done:
Convert the array which has NSString Date to NSDate
Then sort the array with NSDate.
Try this
NSMutableArray *oldArray; //Array which consist of object with date as string.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
if(oldArray.count!=0){
//CONVERT STRING TO DATE
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMM d, yyyy"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
for (int i=0 ;i<oldArray.count;i++)
{
NSMutableDictionary *dict= [oldArray objectAtIndex:i];
NSString *stringDate = [dict objectForKey:#"stringDateKey"];
if(![stringDate isEqualToString:#""]){
NSDate *date = [dateFormat dateFromString:stringDate];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
[newDict addEntriesFromDictionary:dict];
[newDict setObject:date forKey:#"newDate"];
[newArray addObject:newDict];
}
else{
[newArray addObject:dict];
}
}
//SORTING THE ARRAY
NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:#"newDate" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
NSArray *sortedArray = [dataValue sortedArrayUsingDescriptors:sortDescriptors];
}
+ (void)filterAlertsByTime:(NSMutableArray*)alerts {
NSDateFormatter *hourFormatter = [[NSDateFormatter alloc] init];
[hourFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
[alerts sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = [hourFormatter dateFromString:[NSString stringWithFormat:#"%#",obj1[#"expectedDeliveryDate"]]];
NSDate *date2 =[hourFormatter dateFromString:[NSString stringWithFormat:#"%#",obj2[#"expectedDeliveryDate"]]] ;
return [date1 compare:date2];
}];
}
Please edit the date format according to the format of the expectedDeliveryDate string
You can use sort descriptors to sort objects by their dates. So first convert your strings to NSDates and set them on another property of your custom object, and sort them that way.
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"expectedDeliveryDate"
ascending:YES];
NSArray *sortedDeliverDates = [deliveryItems sortedArrayUsingDescriptors:#[descriptor]];
Furthermore NSDate also has a compare: method that will let you compare two dates.

How to sort the Array that contains date in strings in ascending order

I have array of dictionaries ,In every dictionary contains one date parameter . The array of date parameters(contains in dictionaries) as follow:
[#"16-1-2015 7:00PM",#"15-1-2014 11:30AM",#"14-1-2014 7:00PM",
#"15-1-2015 6:30AM ".#"16-1-2015 8:30PM"]
I need output like :
[#"16-1-2015 8:30PM",#"16-1-2015 7:00PM",#"15-1-2015 6:30AM ",
#"15-1-2014 11:30AM",#"14-1-2014 7:00PM"];
You could try this:
NSArray *dateStringArray = #[ #"16-1-2015 7:00PM", #"15-1-2014 11:30AM", #"14-1-2014 7:00PM", #"15-1-2015 6:30AM ", #"16-1-2015 8:30PM" ];
- (NSArray *)sortDateStringArray:(NSArray *)dateStringArray
{
NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:#"dd-MM-yyyy h:mma"];
NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSDate *date1 = [dateFormater dateFromString:obj1];
NSDate *date2 = [dateFormater dateFromString:obj2];
return [date2 compare:date1];
}];
return sortedArray;
}
I think it better convert your dateString to NSDate then compare
Hope this help !!!
Store the dates as NSDate objects in an NSMutableArray, then use -[NSArray sortedArrayUsingSelector:] or -[NSMutableArray sortUsingSelector:] and pass #selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)
Or
If I have an NSMutableArray of objects with a field "beginDate" of type NSDate I am using an NSSortDescriptor as below:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
please visit this question: here

How to convert NSArray to NSDate

I am having an array which having a date. I want to convert the array into NSDate. Then converted NSDate are stored in an another array.This is my array.
uniqueItems (
"2015-02-17",
"2015-02-09",
"2015-02-02",
"2015-01-27",
"2015-01-19",
"2015-01-12"
)
How to convert this array to NSDate, And store in to another array. Help me in coding.
Suppose you have an array as below:
NSArray *ary = [NSArray arrayWithObjects:#"2015-02-17",#"2015-02-09",#"2015-02-02", nil];
To convert each string into date:-
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
for(int i =0;i<ary.count;i++){
NSDate *d = [[NSDate alloc]init];
d = [dateFormatter dateFromString:ary[i]];
}
If you want to use NSDateFormate, you can also use in loop also.
First convert your NSString to NSDate
NSArray *arrr = #[ #"2015-02-17",
#"2015-02-09",
#"2015-02-02",
#"2015-01-27",
#"2015-01-19",
#"2015-01-12"];
NSMutableArray *arrDates = [[NSMutableArray alloc]init];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
for (int i = 0; i<arrr.count; i++) {
[arrDates addObject:[df dateFromString:arrr[i]];;
}
NSLog(#"%#",arrDates);
now sort array for dates because your array contains NSDate Objects. you don't have key so do not pass any key
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
sortDescriptorWithKey:#""
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedDateArray = [arrDates sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"%#",sortedDateArray);
I can understand as you are a newbie,Follow these steps but remember to get the understanding first:-
1.Enumerate your array to get all the strings(dates for your understanding),and add those to another array you want, like this:-
for (NSString *dateString in yourArrayofDates) {
NSDate *date=[self getDateFromDateString:dateString];
[yourAnotherDateArray addObject:date];
}
2.Add a method to get the NSDate from your string,like this:-
-(NSDate *)getDateFromDateString :(NSString *)dateString {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;
}

Sorting the array ,it contains Date,month

I want to sort array according to Dates and Months value.I am using this code
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc]initWithKey:#"self" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject:descriptor];
revereseorder=[dateAarray sortedArrayUsingDescriptors:descriptors];
NSLog(#"date order %#",revereseorder);
I have got the response like below:
date order (
"01-11-2014",
"01-12-2014",
"02-11-2014",
"02-12-2014",
"03-11-2014",
"03-12-2014",
"04-11-2014",
"04-12-2014",
"05-11-2014",
"05-12-2014",
"06-11-2014",
"06-12-2014",
"07-11-2014",
"07-12-2014",
"08-11-2014",
"08-12-2014",
"09-11-2014",
"09-12-2014",
"10-11-2014",
"10-12-2014",
"11-11-2014",
"11-12-2014",
"12-11-2014",
"12-12-2014",
"13-11-2014",
"13-12-2014",
"14-11-2014",
"15-11-2014",
"16-11-2014",
"17-11-2014",
"18-11-2014",
"19-11-2014",
"20-11-2014"
)
but i need to display the response current date to descending order based on the current month.Can you please suggest me how can its solve? thank you#
You'll need to convert the strings into actual NSDate objects if you want to sort them properly.
You can use the comparator function to sort them like this...
NSArray *dateStringArray = //your array...
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"dd-MM-yyyy";
NSArray *sortedArray = [dateStringArray sortedArrayUsingComparator:^(NSString *string1, NSString *string2) {
NSDate *date1 = [dateFormatter dateFromString:string1];
NSDate *date2 = [dateFormatter dateFromString:string2];
return [date1 compare:date2];
}];
If you want descending order then just change the last line of the comparator to...
return [date2 compare:date1];
Try this:
NSDateFormatter *fmtdt = [[NSDateFormatter alloc] init];
[fmtdt setDateFormat:#"dd-MM-yyyy"];
NSComparator compareTimes = ^(id string1, id string2)
{
NSDate *time1 = [fmtdt dateFromString:string1];
NSDate *time2 = [fmtdt dateFromString:string2];
return [time1 compare:time2];
};
NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:compareTimes];
[yourArray sortUsingDescriptors:#[sortDesc]];
NSDateFormatter is the easy way, but if you do not want to use NSDateFormatter, then you have to tokenize each date by '-' and sort, this requires more processing though.
NSArray *token = [string componentsSeparatedByString: #"-"];

Resources