Last Updated: September 09, 2019
·
1.835K
· IronLeash

Creating NSDate from NSString and sorting

If your backend is delivering you dates with an unproper format(Anything else then unix timestamp).You have to cast those to NSDate objects with NSDateFormatter in order to sort them in ascending or descending order.In the example above the temporary array model objects contain a date property as string in the format 20130912 and the time is saved in another property like 2215.First we create proper NSDate objects out of those separate strings and then sort them.

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyyMMdd HHmm"];

NSArray *sortedArray = [temporaryArray sortedArrayUsingComparator: ^(CUReservation *obj1, CUReservation *obj2) {

    NSString *date1String = [NSString stringWithFormat:@"%@ %@",obj1.startdate, obj1.starttime];
    NSDate *reservation1date = [formatter dateFromString:date1String];

    NSString *date2String = [NSString stringWithFormat:@"%@ %@",obj2.startdate, obj2.starttime];
    NSDate *reservation2date = [formatter dateFromString:date2String];

    if (reservation1date && reservation2date)
    {
        if ([reservation1date compare:reservation2date] == NSOrderedDescending) {
            return (NSComparisonResult)NSOrderedDescending;

        }
        else
        {
            return (NSComparisonResult)NSOrderedAscending;
        }
    }
    else
    {
        return (NSComparisonResult)NSOrderedAscending;
    }
}];

1 Response
Add your response

Why not using models and performing date conversion on import from backend? Sorting then can be one liner and It would help you to clean the code from backend non-sense. Check Mantle, it's pretty slick.

over 1 year ago ·