Encore PTL
Encore PTL

Reputation: 8214

Create an Array of NSDates like in Ruby

I want to create an array of NSDates starting from today to next month. This can easily be done in Ruby using Time.now..(Time.now + 30.days)

How can I create an array of dates just like in Ruby in Objective C?

Upvotes: 1

Views: 820

Answers (3)

jscs
jscs

Reputation: 64002

Any ObjC solution is unfortunately going to be far more verbose than that Ruby code.

The correct way to make the calculation is with NSDateComponents:

NSMutableArray * dateArray = [NSMutableArray array];
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * plusDays = [NSDateComponents new];
NSDate * now = [NSDate date];
for( NSUInteger day = 0; day < NUMDAYS; day++ ){
    [plusDays setDay:day];
    [dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]];
}

To make the procedure more convenient (if you need to do it more than a few times), you could put this loop into a category method on NSCalendar, with NUMDAYS replaced with the argument and substituting self for cal.

Upvotes: 5

Daddy
Daddy

Reputation: 9035

After much downvoting and commenting, here's my REVISED answer...

-(NSDate *)nextDayFromDate:(NSDate *)originalDate {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [NSDateComponents new];
    dateComponent.day = 1;
    NSDate *tomorrow = [calendar dateByAddingComponents:dateComponent toDate:originalDate options:0];
    return tomorrow;
}

NSMutableArray *dateArray = [NSMutableArray array];
NSDate *now = [NSDate date];
[dateArray addObject:now];
for (int i=0;i<31;i++) {
    NSDate *firstDate = [dateArray objectAtIndex:i];
    NSDate *newDate = [self nextDayFromDate:firstDate];
    [dateArray addObject:newDate];
}

What this does is use the NSCalendar API to add a "day interval" to any given NSDate. Add "Now" to the array, then do a loop 30 times, each time using the previous NSDate object as input to the logic.

Upvotes: 2

Andrew Madsen
Andrew Madsen

Reputation: 21383

There's nothing built in to do this quite as concisely as the Ruby you've posted. Breaking the problem down, you need a way to get the day after a particular date. Here's a function that will do that:

NSDate *CalendarDayAfterDate(NSDate *date)
{
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:date options:0];
}

Next, you need to get an array of days one after the other:

NSDate *today = [NSDate date];
NSMutableArray *dates = [NSMutableArray arrayWithObject:today];
for (NSUInteger i=0; i<30; i++) {
    NSDate *tomorrow = CalendarDayAfterDate(today);
    [dates addObject:tomorrow];
    today = tomorrow;
}

Upvotes: 2

Related Questions