Skip to content

Commit

Permalink
Adds beginningOfWeek and beginningOfDay instance methods
Browse files Browse the repository at this point in the history
  • Loading branch information
billymeltdown committed Nov 16, 2009
1 parent 0f508f1 commit a6c41f5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions NSDate+Helper.h
Expand Up @@ -23,4 +23,7 @@
+ (NSString *)stringForDisplayFromDate:(NSDate *)date;
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed;

- (NSDate *)beginningOfWeek;
- (NSDate *)beginningOfDay;

@end
31 changes: 31 additions & 0 deletions NSDate+Helper.m
Expand Up @@ -146,4 +146,35 @@ + (NSString *)stringForDisplayFromDate:(NSDate *)date {
return [self stringForDisplayFromDate:date prefixed:NO];
}

- (NSDate *)beginningOfWeek {
// largely borrowed from "Date and Time Programming Guide for Cocoa"
// we'll use the default calendar and hope for the best

NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];

/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
NSDate *beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
[componentsToSubtract release];

//normalize to midnight, extract the year, month, and day components and create a new date from those components.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:beginningOfWeek];
return [calendar dateFromComponents:components];
}

- (NSDate *)beginningOfDay {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:self];
return [calendar dateFromComponents:components];
}

@end

0 comments on commit a6c41f5

Please sign in to comment.