Cocoa - 计算两个日期之间的工作日

问题描述 投票:0回答:1

我是可可编程的新手,我想知道如何获得迄今为止的工作日数。所以只有周一到周五。谢谢。

ios objective-c date cocoa nsdate
1个回答
3
投票
NSDate *startDate = ...;
NSDate *stopDate = ...;

NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = @"yyyy-MM-dd";
startDate = [df dateFromString:[df stringFromDate:startDate]]; // get start of the day

NSDateComponents *comps = [NSDateComponents new];
comps.day = 1; // one day in NSDateComponents

NSUInteger count = 0;
while ([stopDate timeIntervalSinceDate:startDate] >= 0) {

    NSInteger weekday = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:startDate].weekday;

    if (weekday != 1 && weekday != 6) ++count; // filter out weekend days - 6 and 1

    startDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:startDate options:0]; // increment start day
}
© www.soinside.com 2019 - 2024. All rights reserved.