我正在 Cocoa 中创建报告生成器,我需要生成方便的日期范围,例如“今天”、“本周”、“本月”、“今年”等。
有没有好的方法来做到这一点?到目前为止,这是我的骨架:
@interface DateRange : NSObject
{
NSDate startDate;
NSDate endDate;
}
@property (nonatomic, retain) NSDate * startDate;
@property (nonatomic, retain) NSDate * endDate;
+ (DateRange *)rangeForDayContainingDate:(NSDate *)date;
+ (DateRange *)rangeForWeekContainingDate:(NSDate *)date;
+ (DateRange *)rangeForMonthContainingDate:(NSDate *)date;
+ (DateRange *)rangeForYearContainingDate:(NSDate *)date;
@end
一些示例用例如下:
DateRange * thisWeek = [DateRange rangeForWeekContainingDate:[NSDate date]];
DateRange * thisYear = [DateRange rangeForYearContainingDate:[NSDate date]];
本质上,我希望返回的DateRange
对象包含目标日期周围的周、月或年的开始和结束日期。例如(在伪代码中):
NSDate * today = [August 25, 2009];
DateRange * thisWeek = [DateRange rangeForWeekContainingDate:today];
assert(thisWeek.startDate == [August 23, 3009]);
assert(thisWeek.endDate == [August 29, 3009]);
更新:
感谢Kendall Helmstetter Geln 提供的答案,我能够完成这项工作。这是一周范围的完整方法:
+ (DateRange *)rangeForWeekContainingDate:(NSDate *)date
{
DateRange * range = [[self alloc] init];
// start of the week
NSDate * firstDay;
[[self calendar] rangeOfUnit:NSWeekCalendarUnit
startDate:&firstDay
interval:0
forDate:date];
[range setStartDate:firstDay];
// end of the week
NSDateComponents * oneWeek = [[NSDateComponents alloc] init];
[oneWeek setWeek:1];
[range setEndDate:[[self calendar] dateByAddingComponents:oneWeek
toDate:firstDay
options:0]];
[oneWeek release];
return [range autorelease];
}