如何在一个月或两个NSDate之间获得周末数? 我试着用
做一些技巧 calendar.components( NSCalendarUnit.WeekCalendarUnit, fromDate: startDate, toDate: endDate, options: nil)
但没有结果
答案 0 :(得分:2)
NSInteger count = 0;
NSInteger saturday = 7;
// Set the incremental interval for each interaction.
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
// Using a Gregorian calendar.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = fromDate;
// Iterate from fromDate until toDate
while ([currentDate compare:toDate] == NSOrderedAscending) {
NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:currentDate];
if (dateComponents.weekday == saturday) {
count++;
}
// "Increment" currentDate by one day.
currentDate = [calendar dateByAddingComponents:oneDay
toDate:currentDate
options:0];
}
NSLog(@"count = %d", count);
答案 1 :(得分:2)
根据TENSRI,我使用swift编写代码
func numberOfWeekdaysBeetweenDates(#startDate:NSDate,endDate:NSDate)->Int{
var count = 0
var oneDay = NSDateComponents()
oneDay.day = 1;
// Using a Gregorian calendar.
var calendar = NSCalendar.currentCalendar()
var currentDate = startDate;
// Iterate from fromDate until toDate
while (currentDate.compare(endDate) != .OrderedDescending) {
var dateComponents = calendar.components(.WeekdayCalendarUnit, fromDate: currentDate)
if (dateComponents.weekday == 1 || dateComponents.weekday == 7 ) {
count++;
}
// "Increment" currentDate by one day.
currentDate = calendar.dateByAddingComponents(oneDay, toDate: currentDate, options: nil)!
}
return count
}