Devang
Devang

Reputation: 11338

iPhone : How to find Dates between two selected dates?

In my app, I am getting two dates.

For Example,

1st Date : 28-10-2011

2nd Date : 2-11-2011

Now I want to all dates between this two selected date.

So it should be,

28-10-2011

29-10-2011

30-10-2011

1-11-2011

2-11-2011

How can I get this using NSDate?

Upvotes: 0

Views: 2163

Answers (4)

syclonefx
syclonefx

Reputation: 2990

Look at NSDateComponents and dateByAddingComponents:toDate:options:, this is what I use and it works pretty good. Make sure to watch out for years that are leap years.

UPDATE: I would use thomas's example. It works better than mine and it is a lot easier to read.

Upvotes: 3

aahsanali
aahsanali

Reputation: 3547

NSDate *today = [NSDate date];
NSDate *startDate = [NSDate date];
NSDate  *endDate = [today addTimeInterval:10.0*60.0*60.0*24.0]; // end date 10 days ahead
while (YES) {

    startDate= [startDate addTimeInterval:1.0*60.0*60.0*24.0];
    NSLog(@"%@   --  %@",endDate,startDate);

    if([startDate compare:endDate]==NSOrderedDescending) break;
}

Upvotes: 0

thomas
thomas

Reputation: 5649

try dateWithTimeInterval:SinceDate:

NSMutableArray dates = [NSMutableArray array];
NSDate *curDate = startDate;
while([curDate timeIntervalSince1970] <= [endDate timeIntervalSince1970]) //you can also use the earlier-method
{
    [dates addObject:curDate];
    curDate = [MSDate dateWithTimeInterval:86400 sinceDate:curDate]; 86400 = 60*60*24
}
//here maybe an additional check if the enddate has to be inserted or not

Upvotes: 6

jbat100
jbat100

Reputation: 16827

You can convert your strings to NSDate objects using NSDateFormatter, then use NSDate's ealierDate: and laterDate: methods to compare them.

Upvotes: 0

Related Questions