objective-c - 一周内所有 NSDate 的数组

标签 objective-c ios ios5 nsdate

我想要一个函数,该函数将周数作为输入并返回该特定周创建的所有 NSDate 的数组。

像这样:

-(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 */

如何以简单的方式做到这一点?

最佳答案

这个解决方案完全依赖于 NSCalendar,没有对用户的日历做任何假设。

-(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;
}

关于objective-c - 一周内所有 NSDate 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957200/

相关文章:

iphone - iOS 5 中 Xcode 4.2 中的新 "objects library"

iphone - 如何将可变数组的对象以数组的形式存储到另一个可变数组中。?

ios - 从另一个 anchor 在背景中缩放动画

ios - 如何更改 UISegmentedcontrol 标题的字体大小?

ios - cellForRowAtIndexPath : method in UITableViewDelegate

iphone - 如何在单个 tableviewcontroller 中有主题和子主题?

iphone - 用 for 循环中的数据填充 NSMutableArray

objective-c - 使用常量 NSString 作为 NSUserDefaults 的键

ios - 为什么信标会导致蓝牙不断切换?

iphone - NSData dataWithContentsOfFile 仪器 100% 泄漏