2012-12-07 37 views
1

我需要在特定時間段內從核心數據中獲取對象;即weekly,monthly,yearly在Objective-C的特定時間間隔內增加NSDateComponents的最佳方法是什麼?

然後我會喂從部件所產生的日期,一個predicate這樣的:

[NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@", 
           intervalStartDate, intervalEndDate]; 

間隔/週期的示例:

  start   end   start   end 
weekly Jan 2, 2012 to Jan 08, 2012, Jan 9, 2012 to Jan 15, 2012, etc. 
monthly Jan 1, 2012 to Jan 31, 2012, Feb 1, 2012 to Feb 29, 2012, etc. 
yearly Jan 1, 2011 to Dec 31, 2011, Jan 1, 2012 to Dec 31, 2012, etc. 

有了這些,期間,能夠得到的特定對象那段時間。

我的問題是,我不知道什麼是增加日期組件的最佳方式。我必須考慮閏年等。

實現此目標的最佳方法是什麼?

+0

使用datecomponents打破... –

回答

2

只要你使用正確的NSCalendar只要你把日期相互獨立的各個計算,得到的日期應該罰款。

NSDateComponents *dateOffset = [[NSDateComponents alloc] init]; 
[dateOffset setWeek:1]; // weekly 
// [dateOffset setMonth:1]; // monthly 
// [dateOffset setYear:1]; // yearly 

NSDate *endDate = [gregorian dateByAddingComponents:dateOffset toDate:startDate options:0]; 
+0

不錯!我不知道'dateByAddingComponents'。 – Gerstmann

1

只要您使用NSGregorianCalendar,例如,

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

你的日期計算應該利用該日曆的微妙之處(真的很古怪)。

例如:

// get your start date 
NSDateComponents *components = [NSDateComponents new]; 
components.day = 1; 
components.month = 5; 
components.year = 2012; 

NSCalendar *gregorian = [[NSCalendar alloc] 
         initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *date = [gregorian dateFromComponents:components]; 

// add 7 days 
NSDateComponents *addWeekComps = [NSDateComponents new]; 
components.day = 7; 
NSDate *weekAddedDate = [gregorian dateByAddingComponents:addWeekComps toDate:date options:0]; 
相關問題