开发者社区> 问答> 正文

计算出一个月内有几个星期

我想要计算出一个月内的星期。我找到在IOS5实现的方法了,但是在IOS6中不知道应该怎么办?

- (int)weeksOfMonth:(int)month inYear:(int)year
{
    NSCalendar *cCalendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setMonth:month];
    [components setYear:year];

    NSRange range = [cCalendar rangeOfUnit:NSDayCalendarUnit
                               inUnit:NSMonthCalendarUnit
                              forDate:[cCalendar dateFromComponents:components]];

    cCalendar = [NSCalendar currentCalendar];
    [cCalendar setMinimumDaysInFirstWeek:4];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier:@"fr"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSMutableSet *weeks = [[NSMutableSet alloc] init ];

    for(int i = 0; i < range.length; i++)
    {
        NSString *temp = [NSString stringWithFormat:@"%4d-%2d-   %2d",year,month,range.location+i];
        NSDate *date = [dateFormatter dateFromString:temp ];
        int week = [[cCalendar components: NSWeekOfYearCalendarUnit fromDate:date] weekOfYear];
        [weeks addObject:[NSNumber numberWithInt:week]];
    }

    return [weeks count];
}

结果在ios5中返回了5,在ios6中返回了6,这应该怎么解决?

展开
收起
爵霸 2016-03-24 11:05:55 3396 0
1 条回答
写回答
取消 提交回答
  • 我更新XCode后没有IOS5了,但是我不知道你有没有看这段代码。这段代码的意思也就是说循环遍历当前月的每一日,取每一日所在在年周数放入set中。
    比如3月份,3月1号是2013年第9周,而三月31号是2013年第14周,也就说的确是6周。
    我觉得Ios5中返回5的原因可能是个系统bug被修复了。
    ------------------------------------
    当然还有种方法:
    [cCalendar setMinimumDaysInFirstWeek:4];//通过这个参数设置首周的长度
    int week = [[cCalendar components: NSWeekOfMonthCalendarUnit fromDate:date] weekOfMonth];//通过这个算当前日在周号

    比如说首周长度为4的时候,周号为{0,1,2,3,4,5}
    比如说首周长度为1的时候,周号为{1,2,3,4,5,6}
    然后自己做判断,过虑周号为0的周,这样就返回5了。

    2019-07-17 19:12:19
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载