[英]iPhone : How to find Dates between two selected dates?
In my app, I am getting two dates. 在我的应用中,我有两个约会。
For Example, 例如,
1st Date : 28-10-2011
1st Date:28-10-2011
2nd Date : 2-11-2011
2nd Date:2-11-2011
Now I want to all dates between this two selected date. 现在,我要选择这两个选定日期之间的所有日期。
So it should be, 应该是这样
28-10-2011
28-10-2011
29-10-2011
2011年10月29日
30-10-2011
30-10-2011
1-11-2011
1-11-2011
2-11-2011
2011年2月11日
How can I get this using NSDate? 如何使用NSDate获得此功能?
try dateWithTimeInterval:SinceDate:
尝试
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
Look at NSDateComponents
and dateByAddingComponents:toDate:options:
, this is what I use and it works pretty good. 看一下
NSDateComponents
和dateByAddingComponents:toDate:options:
这是我使用的,效果很好。 Make sure to watch out for years that are leap years. 确保当心是years年的年份。
UPDATE: I would use thomas's example. 更新:我将使用托马斯的例子。 It works better than mine and it is a lot easier to read.
它比我的要好,而且阅读起来也容易得多。
您可以使用NSDateFormatter将字符串转换为NSDate对象,然后使用NSDate的ealierDate:和LaterDate:方法进行比较。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.