如何获得一个月内或两个 NSDate 之间的周末数? 我试着用
做一些技巧 calendar.components( NSCalendarUnit.WeekCalendarUnit, fromDate: startDate, toDate: endDate, options: nil)
但是没有结果
最佳答案
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);
关于ios - 一个月中的周末天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28320719/