我正在使用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