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 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置