问题
I would like to have a function that takes a week number as input and returns an array of all the NSDates that this specific week is made by.
Something like this:
-(NSArray*)allDatesInWeek:(int)weekNumber {
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setFirstWeekday:2];
NSDateComponents *todayComp = [calendar components:NSYearCalendarUnit fromDate:today];
int currentyear = todayComp.year;
/* Calculate and return the date of weekNumber for current year */
}
How can this be done in a simple way?
回答1:
Tested.
-(NSArray*)allDatesInWeek:(int)weekNumber {
// determine weekday of first day of year:
NSCalendar *greg = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *coms = [[NSDateComponents alloc] init];
comps.day = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [greg dateByAddingComponents:comps toDate:today];
const NSTimeInterval kDay = [tomorrow timeIntervalSinceDate:today];
comps = [greg components:NSYearCalendarUnit fromDate:[NSDate date]];
comps.day = 1;
comps.month = 1;
comps.hour = 12;
NSDate *start = [greg dateFromComponents:comps];
comps = [greg components:NSWeekdayCalendarUnit fromDate:start];
if (weekNumber==1) {
start = [start dateByAddingTimeInterval:-kDay*(comps.weekday-1)];
} else {
start = [start dateByAddingTimeInterval:
kDay*(8-comps.weekday+7*(weekNumber-2))];
}
NSMutableArray *result = [NSMutableArray array];
for (int i = 0; i<7; i++) {
[result addObject:[start dateByAddingTimeInterval:kDay*i]];
}
return [NSArray arrayWithArray:result];
}
This assumes the first day of the week is Sunday, as stated in the NSDate API. Tweak if desired.
回答2:
This solution relies entirely on NSCalendar without making any assumptions about the user's calendar.
-(NSArray*)allDatesInWeekContainingDate:(NSDate*)referenceDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger ordinalityOfInput = [calendar ordinalityOfUnit:NSWeekdayCalendarUnit
inUnit:NSWeekCalendarUnit
forDate:referenceDate];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
componentsToAdd.day = -1 * (ordinalityOfInput - 1);
NSDate *startDate = [calendar dateByAddingComponents:componentsToAdd toDate:referenceDate options:0];
NSInteger numDaysInWeek = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
NSMutableArray *allDays = [NSMutableArray arrayWithCapacity:numDaysInWeek];
NSDateComponents *curDayOffset = [[NSDateComponents alloc] init];
for (int curDay=0; curDay < numDaysInWeek; curDay++) {
curDayOffset.day = curDay;
[allDays addObject:[calendar dateByAddingComponents:curDayOffset toDate:startDate options:0]];
}
return allDays;
}
来源:https://stackoverflow.com/questions/10957200/array-of-all-nsdate-for-a-week