繁体   English   中英

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

[英]What is the best way to increment NSDateComponents in specific intervals in Objective-C?

我需要在特定时间段内从核心数据中获取对象; 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.

有了这些,我可以在那个时间段内获得特定的对象。

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

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

只要您使用正确的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];

只要您使用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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM