一周内所有NSDate的数组 [英] Array of all NSDate for a week
本文介绍了一周内所有NSDate的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望有一个函数,它将一个星期的数字作为输入,并返回由此特定周制作的所有NSDate的数组。
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.
类似于这个:
-(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?
推荐答案
经过测试。
-(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];
}
这假设一周的第一天是星期天,如NSDate所述API。如果需要调整。
This assumes the first day of the week is Sunday, as stated in the NSDate API. Tweak if desired.
这篇关于一周内所有NSDate的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文