我正在使用NSDateComponents和NSCalendar獲取兩個日期之間的日期。NSDateComponents在兩個日期之間獲取日期的日期屬性不正確
// Get dates between before and after
NSDateComponents *betweenDateComponents = [calendar components:componentFlags
fromDate:afterDate
toDate:beforeDate
options:0];
然後我有一個簡單的循環,是基於組件的天屬性:
for (int i = 1; i < betweenDateComponents.day; ++i) {
這完美的作品時,我所有的一個月工作了一個星期,或者。如果按星期過濾,則日期屬性日誌記錄爲6.如果按月過濾日期屬性爲29,但由於某種原因,當我按年份過濾時,日期屬性記錄爲29而不是364.
爲什麼當我嘗試與一年的工作時,這一天的財產總是錯誤的?
這裏是我的所有代碼,直到for循環我上面包括:
// Set the date components according to the type of filter we're doing
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [NSDateComponents new];
if (filterType == CommentFilterTypeWeeklyByDay) {
[components setDay:-6];
} else if (filterType == CommentFilterTypeMonthlyByDay) {
[components setDay:-29];
} else if (filterType == CommentFilterTypeYearlyByMonth) {
[components setDay:-364];
}
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
// Zero out before and after dates
NSDate *beforeDate = [NSDate date];
NSDateComponents *zeroComponents = [[NSCalendar currentCalendar] components:componentFlags fromDate:beforeDate];
beforeDate = [calendar dateFromComponents:zeroComponents];
NSDate *afterDate = [calendar dateByAddingComponents:components toDate:beforeDate options:0];
zeroComponents = [[NSCalendar currentCalendar] components:componentFlags fromDate:afterDate];
afterDate = [calendar dateFromComponents:zeroComponents];
NSMutableArray *dates = [NSMutableArray new];
[dates addObject:afterDate];
// Get dates between before and after
NSDateComponents *betweenDateComponents = [calendar components:componentFlags
fromDate:afterDate
toDate:beforeDate
options:0];
NSLog(@"%d", betweenDateComponents.day);
for (int i = 1; i < betweenDateComponents.day; ++i) {
因爲你的組件包括'NSYearCalendarUnit'和'NSMonthCalendarUnit',我懷疑你將不得不使用'month'和'year',而不僅僅是'day'。這些組件是累積的,不是獨立的。 – 2014-10-28 17:33:43
這工作。我改變了componentFlags只包含NSYearCalendarUnit和NSDayCalendarUnit。 day屬性現在可以正確記錄。奇怪的是,這隻影響月和年,但不是一週。 – user3344977 2014-10-28 17:38:15