Search code examples
iphoneiosobjective-cnscalendar

List days in calendar year


I am wanting to list (NSLog) all the dates of the Georgian calendar year (2013). I have managed to get the current date using the following:

    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* components = [calendar components:NSDayCalendarUnit
                                               fromDate:currDate];
    NSInteger  day = [components day];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    NSLog(@"%@", dateString);

How can I print out all the dates in 2013?


Solution

  • NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:@"2013-01-01"];
    
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [calendar components:kCFCalendarUnitYear fromDate:date];
    
    while ([components year] < 2014) {
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
        NSString *dateString = [dateFormatter1 stringFromDate:date];
        NSLog(@"%@", dateString);
        date = [NSDate dateWithTimeInterval:60*60*24 sinceDate:date];
        components = [calendar components:kCFCalendarUnitYear fromDate:date];
    }