在Objective-C中以特定间隔增加NSDateComponents的最佳方法是什么?

时间:2012-12-07 09:28:59

标签: objective-c ios nsdate nsdatecomponents

我需要在特定时间段内从核心数据中获取对象;即weeklymonthlyyearly

然后,我会将组件生成的日期提供给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.

通过这些,我可以在那段时间内获得特定的物品。

我的问题是,我不知道增加日期组件的最佳方法是什么。我必须考虑闰年等。

实现这一目标的最佳方式是什么?

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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];
相关问题