Sorting NSMutablearray by NSString as a date - objective-c

I have an array, which is filled out with string objects. Inside each object is the name of the object and the string, seperated by " - ", ex. "Object1 - 26.05.2012 ". I would like to sort my array by the date in the string, and not the name, descending Is this possible?

As #Vladimir pointed out, it would be much better to separate the name and the string from each other and sort by the date.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd.MM.yyyy"];
for (NSString *str in yourArray)
{
NSRange rangeForDash = [str rangeOfString:#"-"];
NSString *objectStr = [str substringToIndex:rangeForDash.location];
NSString *dateStr = [str substringFromIndex:rangeForDash.location+1];
NSDate *date = [formatter dateFromString:dateStr];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:objectStr, #"object", date, #"date", nil];
[newArray addObject:dic];
}
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
[newArray sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc, nil]];
[sortDesc release];
[formatter release];
newArray will be sorted but will have dictionary objects, each containing 2 strings.

Quick and dirty fix - rearrange the string so that the date is first
str = [[str substringFromIndex:someIndex] stringByAppendingString:[str substringToIndex:someIndex]];
then just switch everything back once the array is sorted.

Related

convert hard code nsstring to nsdate

say i have this nsstring * date = #"13th May-2015"
i want to convert it to something like this #"13/05/2015"
currently i am trying to do it with nsdateformatter:
NSString * dateStr = #"13th May-2015";
NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:#"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr];
NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init];
[dateFormatConverted setDateFormat:#"dd/MM/yyyy"];
NSString * convertedDateString = [dateFormatConverted stringFromDate:date];
NSLog(#"this should be 13/05/2015, %#", convertedDateString);
so i expect the converted date string became to 13/05/2015.
but above code fail to do so....any help with code example would be helpful, thanks guys.
NSString * dateStr = #"13th May-2015";
NSArray *stringComponentArray = [dateStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *workingArray = [NSMutableArray arrayWithArray:stringComponentArray];
NSMutableString *dateString = [[NSMutableString alloc]initWithString:[workingArray firstObject]];
[dateString replaceOccurrencesOfString:#"st" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"nd" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"rd" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[dateString replaceOccurrencesOfString:#"th" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[dateString length])];
[workingArray replaceObjectAtIndex:0 withObject:dateString];
dateStr = [workingArray componentsJoinedByString:#" "];
NSDateFormatter *dateFormatOriginal = [[NSDateFormatter alloc] init];
[dateFormatOriginal setDateFormat:#"dd MM-yyyy"];
NSDate *date = [dateFormatOriginal dateFromString:dateStr];
NSDateFormatter *dateFormatConverted = [[NSDateFormatter alloc] init];
[dateFormatConverted setDateFormat:#"dd/MM/yyyy"];
NSString * convertedDateString = [dateFormatConverted stringFromDate:date];
NSLog(#"this should be 13/05/2015, %#", convertedDateString);
Since your date string doesn't match with any of the iOS Date formatter styles. Uou need to play with the strings.Please have a look into above solution.
13th May-2014 is not "dd MM-yyyy" format.
You have to make sure your input string matches the format string exactly.

How to convert numbers into indicative string

I just want to know how can I can convert the numbers 1, 2 or 3 into First, second or Third ?
Any help would be appreciated.
Try this,
- (NSString *)getOrdinalTextFor:(NSInteger)number {
NSNumber *numberValue = [NSNumber numberWithInteger:number];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterOrdinalStyle];
return [numberFormatter stringFromNumber:numberValue];
}
See this one may be it helps you,
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSString* numberString = [formatter stringFromNumber:[NSNumber numberWithInt: 3]];
NSLog(#"%#",numberString);
enter link description hereDownload Formatter kit from GitHub
TTTOrdinalNumberFormatter *ordinalNumberFormatter = [[TTTOrdinalNumberFormatter alloc] init];
[ordinalNumberFormatter setGrammaticalGender:TTTOrdinalNumberFormatterMaleGender];
NSNumber *number = [NSNumber numberWithInteger:2];
NSString *str = [ordinalNumberFormatter stringFromNumber:number];
NSLog(#"%#", str);
Read up this link, its very helpful: Number Formatting

Sort NSDictionaries in NSMutableArray by NSDate

I have a NSMutableArray with dictionaries, all of the dict's contain a NSDate is form of NSString with key 'Date'. I want to sort the NSDictionaries by the Dates. So for example i have the following state of the array:
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
Dict
Date
20.06.1956 23:39
And I want to sort it, so that it looks like this:
Dict
Date
20.06.1956 23:39
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
I have already experimented with NSSortDescriptor, but without success...
Update:
I have managed to sort the dates, but I came to this problem: In the dicts there is not only dates, also other objects, and what my code does is it only switches the date values between the dicts, instead of switching the complete dicts around. With this, the other values in the dicts get assigned a wrong date, which is very bad. Can anybody help me? Heres my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
for (int ii = 0; ii < [d count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:#"Date"];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(#"%#",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:#"Date"];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(#"before: %#"
""
"after: %#",d,sorted);
[sorted writeToFile:path atomically:YES];
There are many ways to do this, one would be to use NSDate objects instead of NSStrings (or NSStrings formatted according to ISO 8601, so that the lexicographic sort would match the desired sorting). Then you could do:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"Date"
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Or, if you can't (or don't want to) change your data, you can always sort using a block:
[array sortUsingComparator:^(id dict1, id dict2) {
NSDate *date1 = // create NSDate from dict1's Date;
NSDate *date2 = // create NSDate from dict2's Date;
return [date1 compare:date2];
}];
Of course this would probably be slower than the first approach since you'll usually end up creating more than n NSDate objects.
There are a couple of options, one is to put NSDate objects in the dictionary.
One problem with comparing the strings is that you can 't just do a string compare because the year is not in the most significant potion of the string.
So, you will need to write a comparison method to use with:
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
or perhaps:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
The comparator will need to handle the dd.mm.yyyy hh:mm string format.
Other options include adding another dictionary key with an NSDate representation and sorting on that.

Cocoa/Obj-C - Dateformat change

I got an application wich read XML file and extract data of the nodes and put the data into textfields.
One of the node is <date>20110305162831</date>
In my textfield I got: 20110305162831
Whish is not very understandable for enduser...
How can i format it like:
2011/03/05 16:28:31
Is it possible?
Here is my AppControler.m code:
NSMutableArray* dates = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLElement* root = [doc rootElement];
NSXMLElement* root = [doc rootElement];
NSArray* dateArray = [root nodesForXPath:#"//Report/ReportCreationDate" error:nil];
for(NSXMLElement* xmlElement in dateArray)
[dates addObject:[xmlElement stringValue]];
NSString * date = [dates objectAtIndex:0];
[dateTextField setStringValue:date];
[doc release];
[dates release];
If someone can help me, it would be great!
Thanks in advance
Miskia
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSDate* date = [dateFormatter dateFromString: #"20110305163031"];
[dateFormatter setDateFormat: #"yyyy/MM/dd HH:mm:ss"];
NSString* date_str = [dateFormatter stringFromDate: date];

How to split up NSArray into NSDictionary by array object's NSDate day of year?

I have a NSArray, and I sort it by its object's "published" property in descending order, newest first:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"published" ascending:YES];
NSArray *descps = [[NSArray alloc] initWithObjects:[sortDescriptor reversedSortDescriptor], nil];
[storiesLocal sortUsingDescriptors:descps];
[descps release];
[sortDescriptor release];
So now, I want to split this array up by each day, so that I can use it with a UITableView. In my example each date would be a tableview section header.
So if my example sorted array (storiesLocal) had dates like such:
2010-04-05 10:32:00
2010-04-05 06:20:12
2010-04-02 09:23:02
2010-04-02 03:20:34
2010-04-01 04:22:34
Then I would have tableview headers like "April 5", "April 2", "April 1". Therefore each would have 2, 2 and 1 row under each corresponding header
Essentially, my wanted outcome would be an NSDictionary. It's each key would be a date (2010-04-02), each value would be an NSArray of the correct objects to go with it. All of these should be sorted by date. Newest first.
I've gone through about 3 tries and failed every time, ending up deleting the code I wrote.
Edit: since an NSDictionary is an unordered list, it might be better to have an array of dictionaries, each dict including a key for the date and a key for the stories array, since order is very important.
This isn't tested, but try something like:
NSArray *descps as above.
NSDateFormatter *in_formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSDateFormatter *out_formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM d"];
NSString *todayStr =
[formatter release];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (ObjectType *obj in descps) {
NSDate *date = [in_formatter dateFromString:[obj published]];
NSString *day = [out_formatter stringFromDate:date];
NSArray *array = [dict valueForKey:day];
if (array == nil) {
array = [[NSMutableArray alloc] init];
[dict setValue:array forKey:day];
[array release];
}
[array addObject:obj];
}
[in_formatter release];
[out_formatter release];