假设我们使用的是公历日历系统,那么找出两个NSDate
对象之间发生的周末数量的最佳方法是什么?
我当前的方法包括计算两个NSDate
之间的天数,然后除以7,然后得出结果floor()
。这给了我几周,因此,我得到了周末数。因为如果一周还没有完成(除法还有余数),我们将对结果进行floor
运算,因此它将忽略该结果,仅考虑已过去的整周。
任何改进和鲁棒性的建议将不胜感激。
最佳答案
像这样尝试,代码的描述在注释中:
//Assuming this is your dates where you need to determine the weekend in between two dates
NSString *strDate1=@"10-01-2014";
NSString *strDate2=@"19-01-2014";
NSDateFormatter *format=[[NSDateFormatter alloc]init];
[format setDateFormat:@"dd-MM-yyyy"];
NSDate *dt1=[format dateFromString:strDate1];
NSDate *dt2=[format dateFromString:strDate2];
//Now finding the days between two dates
NSUInteger units = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit;
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *com=[cal components:units fromDate:dt1 toDate:dt2 options:0];
NSInteger day1=[com day];
int i=0;
int j=0;
//Now calculating how many weekends(Sat, Sun) are there in the total number of days.
for(i=0; i<=day1; i++)
{
com=[[NSDateComponents alloc]init];
[com setDay:i];
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:com
toDate:dt1 options:0];
[format setDateFormat:@"EEE"];
NSString *satSun=[format stringFromDate:newDate];
if ([satSun isEqualToString:@"Sat"] || [satSun isEqualToString:@"Sun"])
{
j++;
}
}
NSLog(@"Total number of weekends found= %d",j);
关于ios - 两个NSDate之间的周末数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21033314/