我想要两个日期之间特定日期的总计数。我想制作一个返回特定日期总数的函数。 例如:如果我通过星期一,开始日期和结束日期,那么它将返回这些日期之间星期一的总计数。
如果我作为星期一过去一天并且开始日期2014-10-04,结束日期是2014-10-18那么函数应该是星期一的返回计数是2
答案 0 :(得分:1)
我可以告诉你一个简单的逻辑来计算。如果它是星期一(开始日期A),下一个星期一将是7天...所以添加7天到开始日期并检查下一个日期(开始日期B)是否小于结束日期,如果不再添加7几天到(开始日期B)再次检查这是否小于结束日期。相应地计算。做这样的事
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
答案 1 :(得分:1)
我自己解决了问题
-(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
}