DaffodilGirl 2012-11-30 05:30 采纳率: 0%
浏览 2354
已采纳

如何查询一个月中特定的一天?

研究了很久NSDateNSDateFormatterNSCalendar,不知道怎么实现找出一月个中指定一天的功能。比如查询十二月第二个星期一的日期是多少,不知道怎么实现呢?

谢谢指教。

  • 写回答

2条回答 默认 最新

  • DaffodilGirl 2012-11-30 08:53
    关注

    谢谢回答者的答案,我根据得到的回答,实现了。最后这样的

        -(void)findWeekDay:(NSInteger)weekDay forWeek:(NSInteger)week OfMonth:(NSInteger)month OfYear:(NSInteger)year
    {
            NSDateComponents *dateComp = [[NSDateComponents alloc]init];
    [dateComp setYear:year];
    [dateComp setMonth:month];
    [dateComp setDay:1];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *firstDate=[gregorian dateFromComponents:dateComp];  //Sets first date of month.
    firstDate=[self dateToGMT:firstDate];
    NSLog(@"First date: %@",firstDate);
    NSDateComponents *dateComp1 = [gregorian components:NSDayCalendarUnit|NSWeekdayCalendarUnit fromDate:firstDate];
    NSInteger firstWeekDay=[dateComp1 weekday];  //Gets firstday of a week. 1-Sunday, 2-Monday and so on.
    NSLog(@"First Week Day: %d",firstWeekDay);
    NSRange daysInMonth = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:firstDate];   //To get number of days in that month
    NSInteger x;    //days to be added to first date
    if (firstWeekDay < weekDay) {
        x = (weekDay - firstWeekDay) + (7 * (week-1));
    }
    if (firstWeekDay > weekDay) {
        x = (7 - firstWeekDay + weekDay) + (7 * (week-1));
    }
    if (firstWeekDay == weekDay) {
        x = (7 * (week-1));
    }
    if (x > daysInMonth.length) {
        NSLog(@"Invalid Date: %d",x);
    }
    else {
        NSLog(@"Days to be added: %d",x);
        NSDateComponents *dateComp2 = [[NSDateComponents alloc]init];
        [dateComp2 setYear:0];
        [dateComp2 setMonth:0];
        [dateComp2 setDay:x];
        NSDate *desiredDate = [gregorian dateByAddingComponents:dateComp2 toDate:firstDate options:0];
        NSLog(@"Your desired date is: %@",desiredDate);
    }
    }
    
        - (NSDate *)dateToGMT:(NSDate *)sourceDate {
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate];
    return destinationDate;
    }
    

    现在如果查询十二月的第三个星期一调用方法:

      [self findWeekDay:2 forWeek:3 OfMonth:12 OfYear:2012];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题