Reputation: 4506
I'd like to group dates for a given week, with the starting day being what the user chooses in their preferences. For example my preference may be that my work week starts on a Friday, and so Friday to Thursday should be my week. Sunday-Saturday. Monday-Sunday, etc.
So I'd like to present the user with a date picker, and although they can pick any calendar day, I'd like to have the collection of dates start with their starting day.
For example if I pick a random Wednesday next month, and my preferences are for a starting work week of Monday, then my collection of dates should start at Monday. The code must be able to walk backwards 2 days, find that monday, then walk forwards until Sunday.
My strategy was to do just that - loop backwards until the start date is found and simply add 6 days to end on a Saturday.
Before I go about it this way, is there a better way (or maybe some sort of specifics in iOS that would make this easier for me than somewhere else)?
Upvotes: 0
Views: 65
Reputation: 112857
Examine the NSCalendar
class. In particular is the method: setFirstWeekday:
.
Example code:
NSDate *today = [NSDate date]; // Or a date of your choice
NSLog(@"today: %@", today);
NSCalendar *caledar = [NSCalendar currentCalendar];
[caledar setFirstWeekday:5]; // Sunday is 1
NSDate *beginningOfWeek;
[caledar rangeOfUnit:NSWeekCalendarUnit
startDate:&beginningOfWeek
interval:NULL
forDate:today];
NSLog(@"beginningOfWeek: %@", beginningOfWeek);
NSLog output:
today: 2014-07-22 14:45:01 +0000
beginningOfWeek: 2014-07-17 04:00:00 +0000
Upvotes: 1
Reputation: 5655
Have you looked at NSDateComponents
? You can specify a specific day of the week.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *pickedDateComponents = [calendar components:NSCalendarUnitWeekday fromDate:pickedDate];
NSInteger saturday = 7; // In the Gregorian calendar, 1 is Sunday, 2 is Monday, etc..
NSDateComponents *daysUntilSaturdayComponents = [NSDateComponents new];
daysUntilSaturdayComponents.weekday = saturday - pickedDateComponents.weekday;
NSDate *saturdayAfterPickedDate = [calendar dateByAddingComponents:daysUntilSaturdayComponents toDate:pickedDate options:0];
Upvotes: 0