2012-02-06 37 views
3

我正在設置一個對象的timeStamp屬性。現在我只使用[NSDate date]。用戶可能每天創建10個對象。但在UI中,我想按日期放棄它們。所以每一天都會顯示當天創建的所有對象。我怎樣才能做到這一點?現在它試圖匹配我需要能夠組那些天,一爲2/5,2/4,2/1的日期和時間等如何按天分組NSDate對象?

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

回答

1

你的問題制定得相當廣泛。爲了得到一個NSDate對象的日期部分,爲NSString,你可以使用:

NSDate *dateIn = [NSDate date]; 

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

您可以輕鬆更改日期格式。如果你經常調用這些代碼(例如在一個循環中),你可能只想分配和設置日期格式化程序一次。

+0

我知道該做什麼,但我怎麼能比較它們?所以,即使我有Obj1 - 2/5/12 5pm Obj2 - 2/5/12 12pm ..我可以截斷時間並使用@「yyyy-MM-dd」格式將它們組合在一起? – Jon 2012-02-06 01:12:52

+0

使用這種格式,你實際上只採用日期;沒有必要「截斷時間」。 – mvds 2012-02-06 01:45:37

3

可以使用NSDateComponents類來直接訪問NSDate實例的日期,月份和年份。

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]); 

下面是一個NSDateComponents比較方法:

- (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; 
} 

我還沒有測試NSDateComponents比較方法;它會受益於單元測試。