2014-10-28 79 views
1

我对ios相当陌生,想知道如何从日期的NSMutableArray(以字符串形式)提取数组中的所有星期日。对日期数组进行排序以提取每个星期日

所以从我的研究,到目前为止,我发现,我必须从今天的这样

NSDate *now = [NSDate date]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

日起开始,然后“选择”这样的

NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit |  NSHourCalendarUnit fromDate:now];  
NSInteger weekday = [dateComponents 1]; // 1 is sunday right ?! 

在星期天然后返回到过去和每个星期日都把日期放在一个新的阵列中,否则。

NSDate *dateRelease; 
    NSDateFormatter *dateFormatter = [ [ NSDateFormatter alloc ] init ]; 
    [ dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] ]; 
    [ dateFormatter setDateFormat:@"yyyy-MM-dd" ]; 

    for (int i = [ dateFormatter dateFromString:[[[[DessinsManager sharedInstance]imagesList].count ; i > 0; i--){ 

    dateRelease = [ dateFormatter dateFromString:[[[[DessinsManager sharedInstance]imagesList] objectAtIndex:i]dateDrawing] ]; 

    //Check for the sundays here 
    if ([now compare: dateRelease] == NSOrderedDescending ) { 
    //if sundays put in new array 
    } else { 
    //if not sundays then go on with loop 
    } 
    } 

而对于这个我就怎么做的comparaison拿到周日(我的数组从云到今天2013年11月1日)有点糊涂了......

感谢您的帮助

Vv

回答

0

第一家门店日期的,你应该总是存储使用最合适的数据类型的数据NSDate对象:

NSArray *datesAsStrings = ...; 
NSMutableArray *dates = [NSMutableArray new]; 
NSDateFormatter *dateFormatter = [NSDateFormatter new]; 
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 
dateFormatter.dateFormat = @"yyyy-MM-dd"; 
for (NSString *dateStr in datesAsStrings) { 
    NSDate *date = [dateFormatter dateFromString:dateStr]; 
    [dates addObject:dates]; 
} 

,然后滤除星期日:

NSMutableArray *sundays = [NSMutableArray new]; 
[dates enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop)) { 
    NSDate *date = (NSDate *)obj; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit 
              fromDate:date]; 
    if (comps.weekday == 1) 
     [sundays addObject:date]; 
}]; 
+0

感谢您的例子,即使我没有完全重用它,我明白了! – ViVittori 2014-10-28 13:33:49

0

您应该使用- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate方法,该方法返回一个新数组,该数组使用谓词评估原始数据库中的每个对象。

这样一个谓词可以用+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block来构建,也许从Dave DeLong's answer here可以得到一些启发来识别被评估的一天。