iPhone : How to find Dates between two selected dates?

狂风中的少年 提交于 2019-12-02 16:48:17

问题


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?


回答1:


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



回答2:


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.




回答3:


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




回答4:


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;
}


来源:https://stackoverflow.com/questions/7858982/iphone-how-to-find-dates-between-two-selected-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!