3

I am creating an app that needs to put all dates of the year into a uitableview (each date having their own cell). Is there any way to use the nsdate to populate each cell with every date?

Chris
  • 45
  • 2
  • The answers in this question look useful: http://stackoverflow.com/questions/1472386/number-of-days-in-given-year-using-iphone-sdk – jtbandes Aug 21 '11 at 20:46

1 Answers1

0

You will need to create the NSDate instances manually if you need to display all dates from 1 January through 31 December.

The following methods might help with the NSDate instances you need for your UITableView cells:

- (NSInteger)daysInYear:(NSInteger)year {
    if (year % 400 == 0)        return 366;
    else if (year % 100 == 0)   return 365;
    else if (year % 4 == 0)     return 366;
    else                        return 365;
}


- (NSDate *)firstDayInYear:(NSInteger)year {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    [fmt setDateFormat:@"MM/dd/yyyy"];
    NSDate *firstDayInYear = [fmt dateFromString:[NSString stringWithFormat:@"01/01/%d", year]];
    [fmt release];
    return firstDayInYear;
}


- (NSDate *)dateWithDayInterval:(NSInteger)dayInterval sinceDate:(NSDate *)referenceDate {
    static NSInteger SECONDS_PER_DAY = 60 * 60 * 24;
    return [NSDate dateWithTimeInterval:dayInterval * SECONDS_PER_DAY sinceDate:referenceDate];
}

In your tableView:cellForRowAtIndexPath: method you can then instantiate the corresponding NSDate instance:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDate *dateForCell = [self dateWithDayInterval:indexPath.row sinceDate:self.firstDayInYear];
    // ... rest of your method ...
}
pythonquick
  • 10,789
  • 6
  • 33
  • 28
  • Thanks a million. That probably would have taken me another week to figure out. Once I finally quit messing with kal calendar – Chris Aug 22 '11 at 05:42
  • I've noticed that when I put it into a grouped style table view it stops at the seventh (number of cells in each section) and repeats itself in each section. What would be the best way to add the dates in a grouped style uitableview ? Thanks again i appreciate all of the help – Chris Aug 23 '11 at 12:45
  • @pythonquick This is repeating the same day in uitableview all rows. –  Jun 19 '13 at 09:43