我想要做的是获取两个日期之间每月特定日期的次数.
例如:
我想要在2011年11月21日至2013年5月15日期间每月16日过多少次.
在这种情况下,它将是17.
我一直在努力解决这个问题.我知道如何解决这个问题的唯一方法是编写一堆if语句来检查已经过了多少年,然后已经过了多少个月等等.有没有更快的方法,比如使用NSDate或其他什么?
解决方法
好的,这是一个
gist的工作示例.代码的内容是:
const NSCalendarUnit units = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSCalendarCalendarUnit|NSTimeZoneCalendarUnit; NSDateComponents *comps = [calendar components:units fromDate:startDate]; if ([comps day] > wantDay) nextMonth(comps); // Missed the first month [comps setDay:wantDay]; NSInteger count = 0; while (YES) { NSDate *compareDate = [calendar dateFromComponents:comps]; if (!compareDate) { NSLog(@"Failed to create compare date"); return 5; } NSLog(@"Comparing %@",[formatter stringFromDate:compareDate]); if ([compareDate compare:endDate] == NSOrderedDescending) break; count++; nextMonth(comps); }
nextMonth()的位置是:
static void nextMonth(NSDateComponents *comps) { NSInteger month = [comps month]; if (month == 12) { [comps setYear:[comps year] + 1]; [comps setMonth:1]; } else { [comps setMonth:month + 1]; } }
示例输出:
$./dateiter 19990112 19990212 12 2014-01-16 13:06:53.189 dateiter[16740:707] start-date=1999-01-12 00:00:00 +0000,end-date=1999-02-12 00:00:00 +0000,want-day=12 2014-01-16 13:06:53.189 dateiter[16740:707] Comparing 19990112 2014-01-16 13:06:53.190 dateiter[16740:707] Comparing 19990212 2014-01-16 13:06:53.190 dateiter[16740:707] Comparing 19990312 2014-01-16 13:06:53.190 dateiter[16740:707] 2 months $./dateiter 20111121 20130515 16 2014-01-16 13:10:53.318 dateiter[16810:707] start-date=2011-11-21 00:00:00 +0000,end-date=2013-05-15 00:00:00 +0000,want-day=16 2014-01-16 13:10:53.319 dateiter[16810:707] Comparing 20111216 2014-01-16 13:10:53.319 dateiter[16810:707] Comparing 20120116 2014-01-16 13:10:53.319 dateiter[16810:707] Comparing 20120216 2014-01-16 13:10:53.319 dateiter[16810:707] Comparing 20120316 2014-01-16 13:10:53.320 dateiter[16810:707] Comparing 20120416 2014-01-16 13:10:53.320 dateiter[16810:707] Comparing 20120516 2014-01-16 13:10:53.320 dateiter[16810:707] Comparing 20120616 2014-01-16 13:10:53.320 dateiter[16810:707] Comparing 20120716 2014-01-16 13:10:53.321 dateiter[16810:707] Comparing 20120816 2014-01-16 13:10:53.321 dateiter[16810:707] Comparing 20120916 2014-01-16 13:10:53.321 dateiter[16810:707] Comparing 20121016 2014-01-16 13:10:53.322 dateiter[16810:707] Comparing 20121116 2014-01-16 13:10:53.322 dateiter[16810:707] Comparing 20121216 2014-01-16 13:10:53.322 dateiter[16810:707] Comparing 20130116 2014-01-16 13:10:53.322 dateiter[16810:707] Comparing 20130216 2014-01-16 13:10:53.323 dateiter[16810:707] Comparing 20130316 2014-01-16 13:10:53.323 dateiter[16810:707] Comparing 20130416 2014-01-16 13:10:53.323 dateiter[16810:707] Comparing 20130516 2014-01-16 13:10:53.323 dateiter[16810:707] 17 months
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。