Created
March 18, 2012 14:43
-
-
Save mundstein/2074409 to your computer and use it in GitHub Desktop.
Objective-C method to return last or next Monday from date.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(NSDate *) lastMondayBeforeDate:(NSDate*)timeStamp { | |
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; | |
NSDateComponents *comps = | |
[gregorian components:NSWeekdayCalendarUnit fromDate:timeStamp]; | |
NSInteger weekday = [comps weekday]; | |
weekday = weekday==1 ? 6 : weekday-2; // start with 0 on Monday rather than 1 on Sunday | |
NSTimeInterval secondsSinceMondayMidnight = | |
(NSUInteger) [timeStamp timeIntervalSince1970] % 60*60*24 + | |
weekday * 60*60*24; | |
return [timeStamp dateByAddingTimeInterval:-secondsSinceMondayMidnight]; | |
} | |
-(NSDate *) nextMondayAfterDate:(NSDate*)timeStamp { | |
return [[self lastMondayBeforeDate:timeStamp] | |
dateByAddingTimeInterval:60*60*24*7]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment