Ios 如何计算两个日期之间特定日期的计数?
我想要两个日期之间某一天的总计数。我想要做一个函数,返回某一天的总计数。 例如:如果我通过了星期一、开始日期和结束日期,那么它将返回这些日期之间星期一的总计数Ios 如何计算两个日期之间特定日期的计数?,ios,iphone,date,calendar,Ios,Iphone,Date,Calendar,我想要两个日期之间某一天的总计数。我想要做一个函数,返回某一天的总计数。 例如:如果我通过了星期一、开始日期和结束日期,那么它将返回这些日期之间星期一的总计数 如果我将日期作为星期一,开始日期为2014-10-04,结束日期为2014-10-18,那么函数应该是星期一的返回计数为2,我可以告诉你一个简单的计算逻辑。如果是星期一(开始日期A),下一个星期一将是7天后。。。因此,在开始日期加上7天,检查下一个日期(开始日期B)是否小于结束日期,如果不是,再次在开始日期(开始日期B)加上7天,再次检查
如果我将日期作为星期一,开始日期为2014-10-04,结束日期为2014-10-18,那么函数应该是星期一的返回计数为2,我可以告诉你一个简单的计算逻辑。如果是星期一(开始日期A),下一个星期一将是7天后。。。因此,在开始日期加上7天,检查下一个日期(开始日期B)是否小于结束日期,如果不是,再次在开始日期(开始日期B)加上7天,再次检查这是否小于结束日期。据此计算。做这样的事
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = 7;
NSDate *DateWithAdditon = [[NSCalendar currentCalendar]dateByAddingComponents:dateComponents toDate: StartDate
options:0];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *DateWithAdditonString= [ dateFormatter stringFromDate:DateWithAdditon];
NSLog(@"your next monday will be here %@ ",DateWithAdditonString );
//Write code to check wheather the DateWith addition is lesser than the End date if not add another 7 days and increase the count accordingly
我自己找到了解决办法
-(int)countDays:(int)dayCode startDate:(NSDate *)stDate endDate:(NSDate *)endDate
{
// day code is Sunday = 1 ,Monday = 2,Tuesday = 3,Wednesday = 4,Thursday = 5,Friday = 6,Saturday = 7
NSInteger count = 0;
// Set the incremental interval for each interaction.
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
// Using a Gregorian calendar.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = stDate;
// Iterate from fromDate until toDate
while ([currentDate compare:endDate] == NSOrderedAscending) {
NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:currentDate];
if (dateComponents.weekday == dayCode) {
count++;
}
// "Increment" currentDate by one day.
currentDate = [calendar dateByAddingComponents:oneDay
toDate:currentDate
options:0];
}
NSDateComponents* component = [calendar components:NSWeekdayCalendarUnit fromDate:endDate];
int weekDay = [component weekday];
if (weekDay == dayCode) { // Condition if end date contain your day then count should be increase
count ++ ;
}
return count; // Return your day count
}