gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:57:14 24 4
gpt4 key购买 nike

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

最佳答案

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
}

关于objective-c - Cocoa - 计算两个日期之间的工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25524895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com