oOOMIAO 2013-03-07 02:39 采纳率: 10%
浏览 5640
已采纳

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

我想要计算出一个月内的星期。我找到在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,这应该怎么解决?

  • 写回答

1条回答

  • 哈希Map 2013-03-12 09:25
    关注

    我更新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了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献