3

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.

bneely
  • 9,083
  • 4
  • 38
  • 46
Jon
  • 4,732
  • 6
  • 44
  • 67

2 Answers2

4

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.

bneely
  • 9,083
  • 4
  • 38
  • 46
1

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.

mvds
  • 45,755
  • 8
  • 102
  • 111
  • I know who to do that, but how can I compare them? So even if I have Obj1 - 2/5/12 5pm Obj2 - 2/5/12 12pm.. I can truncate the time off and use the @"yyyy-MM-dd" format to group them together? – Jon Feb 06 '12 at 01:12
  • Using the format you are in fact taking only the date only; there is no need to "truncate the time off". – mvds Feb 06 '12 at 01:45