My server is sending some JSON Data which contains date like below:
"date":"2012-09-25"
"date":"2012-09-27"
"date":"2012-09-29"
"date":"2012-09-27"
"date":"2012-09-29"
On client side I need to sort these dates. For achieving this I was converting these strings into a date format but getting crash. Below is the code:
Problem:
In line 2, the date format yyyy-mm-dd is similar to the format that I am receiving from the server. This is okay, in line 3, it works correct ie dateStr converts in date object and adds in newDates array.
But, if change the format from server like 09-25-2012 ie mm-dd-yyyy then line 3 doesn't convert dateStr into date format, hence date becomes nil and in line 4 it get crashed due to adding nil object.
So how can I solve this issue? I need sorted array before displaying it on the List View.
Additionally I am using following code to sort the dates in ascending array.
"date":"2012-09-25"
"date":"2012-09-27"
"date":"2012-09-29"
"date":"2012-09-27"
"date":"2012-09-29"
On client side I need to sort these dates. For achieving this I was converting these strings into a date format but getting crash. Below is the code:
Code:
// dates received from the server, see above for eg
NSArray *myDates = ....
// array to hold date objects
NSMutuableArray *newDates = [[NSMutuableArray alloc] init];
// traverse each string, then convert it into date object then add in newDate
for (NSString *dateStr in myDates)
{
NSDateFormatter *f = [[NSDateFormatter alloc] init]; // line 1
[f setDatFormat@"yyyy-mm-d"]; // line 2
NSDate *date = [f dateFromString:dateStr]; // line 3
[newDates addObject:date]; // line 4
}
Problem:
In line 2, the date format yyyy-mm-dd is similar to the format that I am receiving from the server. This is okay, in line 3, it works correct ie dateStr converts in date object and adds in newDates array.
But, if change the format from server like 09-25-2012 ie mm-dd-yyyy then line 3 doesn't convert dateStr into date format, hence date becomes nil and in line 4 it get crashed due to adding nil object.
So how can I solve this issue? I need sorted array before displaying it on the List View.
Additionally I am using following code to sort the dates in ascending array.
Code:
// logic to sort the date in ascending order
NSSortDescriptor *sortDesc =
[[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES];
[newDates sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc];
for (NSString *date in newDates)
{
NSLog(@"Date = %@", date];
}
Last edited: