Thursday, June 13, 2013

NSCalendar firstWeekday example in Objective C (iOS).

NSCalendar firstWeekday

Returns the index of the first weekday of the receiver.

- (NSUInteger)firstWeekday

Return Value of [NSCalendar firstWeekday]
The index of the first weekday of the receiver.

NSCalendar firstWeekday example.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];

Optional step:
beginningOfWeek now has the same hour, minute, and second as the
original date (today).
To normalize to midnight, extract the year, month, and day components
and create a new date from those components.
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                            fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents: components];

Example of [NSCalendar firstWeekday].
- (NSDate *)firstDateOfWeekWithDate:(NSDate *)date {

    NSCalendar * calendar = [NSCalendar currentCalendar];

    NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];

    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
    [components setDay:-((([weekdayComponents weekday] - [calendar firstWeekday]) + 5 ) % 7)];

    return [calendar dateFromComponents:components];

NSCalendar firstWeekday example.
Ok, so it turns out this is the correct way of doing it:

[[NSCalendar currentCalendar] firstWeekday]

End of NSCalendar firstWeekday example article.