Reputation: 2488
i have a function which returns weekdays by passing any specific day, in my app , monday will be the week start day, it works fine except when settings current day to sunday, in this case the function is returning next weekdays ,
+(NSMutableArray*) getWeekDatesList :(NSDate*) date {
@autoreleasepool {
NSDate *startingDateOfWeek = [self getWeekStartDateWithDate:date];
return [self getWeekDatesListWithStartDate:startingDateOfWeek];
}
},
and function to get week start date is,
+(NSDate*) getWeekStartDateWithDate:(NSDate*) date{
@autoreleasepool {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
[gregorian setFirstWeekday:2]; // 2 monday
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekOfYearCalendarUnit |NSWeekCalendarUnit fromDate:date];
int value =([components day]-([components weekday]-2));
[components setDay:value];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
return beginningOfWeek;
}
}
Example:
settings today as Sunday April 20 2014, am getting week start date as April 21 2014, but expected week start date is April 13 2014
how can i make it work correctly even when current day is set to sunday ?
Thanks
Upvotes: 0
Views: 780
Reputation: 539705
In your calculation you would have to check if [components weekday]
is less or greater
than 2 (Monday) and modify the components accordingly to get the previous Monday.
But you can simplify the calculation to:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// [gregorian setLocale:[NSLocale currentLocale]]; (This is the default.)
[gregorian setFirstWeekday:2]; // 2 = Monday
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *beginningOfWeek;
[gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate:date];
This gives 2014-04-14 00:00:00 +0000 (a Monday) as expected.
Remark: You should check if you really want to set the time zone to GMT. If you don't set a time zone then you will get the beginning of the week according to your local time zone.
Upvotes: 3