Jon
Jon

Reputation: 4732

How to group NSDate objects by day?

I'm setting a timeStamp property for an object. Right now I'm just using [NSDate date]. The user might create 10 objects per day. But in the UI, I want to drop them by date. So each day will show all the objects that were created for that day. How can I do this? Right now it's trying to match the date and time, etc.

Example: 
Obj1 - 2/5/12 5pm
Obj2 - 2/5/12 12pm
Obj3 - 2/4/12 6pm
Obj4 - 2/1/12 1pm

I need to be able to group those by day, one for 2/5, 2/4, and 2/1.

Upvotes: 3

Views: 1146

Answers (2)

bneely
bneely

Reputation: 9093

You can use the NSDateComponents class to be able to directly access the day, month, and year of an NSDate instance.

NSDate *someDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit fromDate:someDate];

NSLog(@"Year: %d", [components year]);
NSLog(@"Month: %d", [components month]);
NSLog(@"Day: %d", [components day]);

Here's an NSDateComponents comparison method:

- (BOOL)isFirstCalendarDate:(NSDateComponents *)first beforeSecondCalendarDate:(NSDateComponents *)second
{
    if ([first year] < [second year]) {
        return YES;
    } else if ([first year] == [second year]) {
        if ([first month] < [second month]) {
            return YES;
        } else if ([first month] == [second month]) {
            if ([first day] < [second day]) {
                return YES;
            }
        }
    }
    return NO;
}

I haven't tested the NSDateComponents comparison method; it would benefit from unit testing.

Upvotes: 4

mvds
mvds

Reputation: 47034

Your question is formulated rather broadly. To get the date part of an NSDate object, as an NSString, you could use:

NSDate *dateIn = [NSDate date];

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyy-MM-dd"];
NSString *stringOut = [fmt stringFromDate:dateIn];
[fmt release];

You can easily change the date format. If you would call this code often (e.g. in a loop) you might want to allocate and set up the date formatter only once.

Upvotes: 1

Related Questions