假设我们使用公历系统,计算两个 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/