【问题标题】:Find all days of a week/month/year and add to NSMutableArray查找一周/月/年的所有日子并添加到 NSMutableArray
【发布时间】:2014-06-21 20:09:39
【问题描述】:

我有一个 NSMutableArray,我希望能够只提取某些时间范围内的行,例如每周、每月或每年。我可以得到一个一周前的日期,所以我会有当前日期和一周前的日期,但我需要能够抓住所有这些天,然后将它们添加到一个数组中,以便我可以搜索它们。

这就是我如何抓住一周前的一天和一天。

-(void)getCalDays {
cal = [NSCalendar currentCalendar];

NSDate *date = [NSDate date];
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:date];
today = [cal dateFromComponents:comps];


   NSLog(@"today is %@", today);
    [self getWeek];
}

-(void)getWeek {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:-6];
    weekDate = [cal dateByAddingComponents:components toDate:today options:0];
    NSLog(@"Week of %@ THRU %@", today, weekDate);
}

那么我怎样才能找到两个日期之间的所有天数并将它们加载到一个数组中呢?

【问题讨论】:

    标签: ios objective-c nsdate nscalendar


    【解决方案1】:

    你正在路上。关键是循环推进组件的日期并从中提取日期。

    NSMutableArray *result = [NSMutableArray array];
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDate *startDate = // your input start date
    NSDate *endDate = // your input end date
    
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:startDate];
    NSDate *date = [cal dateFromComponents:comps];
    
    while (![date isEqualToDate:endDate]) {
        [result addObject:date];
        [comps setDay:(comps.day + 1)];
        date = [cal dateFromComponents:comps];
    }
    

    请注意,这将导致日期集合包含第一个日期,不包含最后一个日期。您可能可以自己解决如何更改边缘条件。

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 2017-11-19
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2014-02-19
      相关资源
      最近更新 更多