我需要创建一个日历,用户可以在几周内滚动。一周的第一天和最后一天将显示为(例如)“6月4日 - 6月10日”。
现在我从一开始就知道我需要NSDate
和NSCalendar
,而且我确实得到了本周的第一天和最后一天,但它看起来非常麻烦而且我是确定需要一种更简单的方法,因为我需要获得更多未来几周的日期。
这是我的代码,它给出了当周第一天和最后一天的day
和month
:
NSDate *today = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit) fromDate:[NSDate date]];
NSDate *beginOfWeek = [today dateByAddingTimeInterval: -1*([comp weekday]-2)*24*3600];
NSDate *endOfWeek = [today dateByAddingTimeInterval:(7-[comp weekday]+2)*24*3600];
NSLog(@"beginWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] day]);
NSLog(@"endWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] day]);
NSLog(@"beginWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] month]);
NSLog(@"endWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] month]);
答案 0 :(得分:1)
我找到了这个,这可能对您有所帮助:http://www.cocoanetics.com/2009/11/add-one-week-skip-weekend/
- (NSDate *)addWeekToDateAndSkipWeekend:(NSDate *)now {
int daysToAdd = 6; // we'll add the 7th later
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:now options:0];
[components setDay:1]; // reuse to skip single days
NSDateComponents *newDateComps; // new componets to get weekday
// do always executed once, so we add the 7th day here
do
{
// add one day
newDate = [gregorian dateByAddingComponents:components toDate:newDate options:0];
newDateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:newDate];
// repeat if the date is Saturday (7) or Sunday (1)
NSLog(@"weekday: %d", [newDateComps weekday]);
} while (([newDateComps weekday]==7)||([newDateComps weekday]==1));
return newDate;
}
理论上,你在[NSDate date]的for循环中运行它,你将返回7th
天,然后你将通过这个运行返回的7th
天并获得下一个..等。
如果您不需要,可能需要进行细微更改,以取消周六+周日的支票。
希望这有帮助!