ios - 两个 NSDate 之间的周末数

标签 ios objective-c nsdate

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

相关文章:

ios - iTunes上的应用提交错误

ios - 用 for 循环填充 NSMutableDictionary,然后它会显示最后加载的值

ios - iOS7 和 Xcode5 中的 MRC

iphone - 消息发送到已解除分配的实例

swift - 如何计算 Swift 中的特定日期(使用 NSDate)

iphone - 可以使用 XCode 通过蓝牙编译/运行 iOS 吗?

IOS TableView :Table View Custom Cell While Scrolling It pre-populates the Value in another cell

objective-c - 设置属性值时是否需要使用临时变量?

swift - 如何在 Swift 中以短格式获取当前日期

ios - 如何正确地将 Last-Modified header 从 HTTP 响应转换为 iOS 上的 NSDate