在两个NSDate之间发生的特定工作日的计数 [英] Count of a specific weekday occurring between two NSDates

查看:162
本文介绍了在两个NSDate之间发生的特定工作日的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查找两个 NSDates 之间发生的特定工作日的计数?

How can I find the count of a specific weekday occurring between two NSDates?

推荐答案

NSDate *fromDate = ...;
NSDate *toDate = ...;
NSUInteger weekDay = ...; // The given weekday, 1 = Sunday, 2 = Monday, ...
NSUInteger result;

// Compute weekday of "fromDate":
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *c1 = [cal components:NSWeekdayCalendarUnit fromDate:fromDate];

// Compute next occurrence of the given weekday after "fromDate":
NSDateComponents *c2 = [[NSDateComponents alloc] init];
c2.day = (weekDay + 7 - c1.weekday) % 7; // # of days to add
NSDate *nextDate = [cal dateByAddingComponents:c2 toDate:fromDate options:0];

// Compare "nextDate" and "toDate":
if ([nextDate compare:toDate] == NSOrderedDescending) {
    // The given weekday does not occur between "fromDate" and "toDate".
    result = 0;
} else {
    // The answer is 1 plus the number of complete weeks between "nextDate" and "toDate":
    NSDateComponents *c3 = [cal components:NSWeekCalendarUnit fromDate:nextDate toDate:toDate options:0];
    result = 1 + c3.week;
}

(此代码假设一周有七天,格雷戈里亚历。
如有必要,代码可能推广到任意日历。)

(The code assumes that a week has seven days, which is true for the Gregorian calendar. If necessary, the code could probably generalized to work with arbitrary calendars.)

这篇关于在两个NSDate之间发生的特定工作日的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆