I'm creating a report generator in Cocoa, and I need to produce convenient date ranges such as "Today", "This Week", "This Month", "This Year", etc.
Is there a good way to do this? Here is my skeleton thus far:
@interface DateRange : NSObject
{
NSDate startDate;
NSDate endDate;
}
@property (assign) NSDate * startDate;
@property (assign) NSDate * endDate;
+ (DateRange *)rangeForDayContainingDate:(NSDate *)date;
+ (DateRange *)rangeForWeekContainingDate:(NSDate *)date;
+ (DateRange *)rangeForMonthContainingDate:(NSDate *)date;
+ (DateRange *)rangeForYearContainingDate:(NSDate *)date;
@end
Some example use cases would be as follows:
DateRange * thisWeek = [DateRange rangeForDayContainingDate:[NSDate date]];
DateRange * thisYear = [DateRange rangeForYearContainingDate:[NSDate date]];
Essentially, I want the returned DateRange
object to contain the start and end dates for the week, month or year surrounding the target date. For example (in pseudocode):
NSDate * today = [August 25, 2009];
DateRange * thisWeek = [DateRange rangeForWeekContainingDate:today];
assert(thisWeek.startDate == [August 23, 3009]);
assert(thisWeek.endDate == [August 29, 3009]);
update:
I was able to get this working thanks to the answer provided by Kendall Helmstetter Geln. Here is the complete method for a one-week range:
+ (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];
}