iPhone : How to find Dates between two selected da

2020-05-01 07:32发布

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?

4条回答
该账号已被封号
2楼-- · 2020-05-01 08:02

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

查看更多
萌系小妹纸
3楼-- · 2020-05-01 08:05

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
查看更多
疯言疯语
4楼-- · 2020-05-01 08:21
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;
}
查看更多
The star\"
5楼-- · 2020-05-01 08:23

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.

查看更多
登录 后发表回答