简单的日历实现:其中firstDay_InMonth代表本月的第一天尾星期几 allDay_InMonth代表本月一共有几天
//星期
NSArray *array = [NSArrayarrayWithObjects:@"日",@"一",@"二",@"三",@"四",@"五",@"六",nil];
for (int i =0; i < 7; i++) {
UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(WIDTH/7 * i,0, WIDTH/7,30)];
label.textAlignment =NSTextAlignmentCenter;
label.font = [UIFontsystemFontOfSize:13];
label.textColor = [UIColordarkTextColor];
label.text = array[i];
[self.bagViewaddSubview:label];
}
//日期
for (NSInteger i =self.firstDay_InMonth; i<self.allDay_InMonth+self.firstDay_InMonth; i++) {
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];
[button setTitle:[[NSNumbernumberWithInteger:i-self.firstDay_InMonth+1]stringValue] forState:UIControlStateNormal];
button.backgroundColor = [UIColorwhiteColor];
[button setTitleColor:[UIColordarkGrayColor] forState:UIControlStateNormal];
NSInteger n = i/7;
button.frame = CGRectMake((i-n*7)*WIDTH/7+1, WIDTH/7*n+30+1, WIDTH/7-2, WIDTH/7-2);
[self.bagViewaddSubview:button];
}
}
//第一天是周几
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
NSCalendar *calendar = [NSCalendarcurrentCalendar];
[calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
NSDateComponents *component = [calendarcomponents:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay)fromDate:date];
[component setDay:1];
NSDate *firstDayOfMonthDate = [calendar dateFromComponents:component];
NSUInteger firstWeekDay = [calendarordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitWeekOfMonthforDate:firstDayOfMonthDate];
return firstWeekDay - 1;
}
//当月总天数
- (NSInteger)totaldaysInMonth:(NSDate *)date{
NSRange daysInOfMonth = [[NSCalendarcurrentCalendar] rangeOfUnit:NSCalendarUnitDayinUnit:NSCalendarUnitMonthforDate:date];
return daysInOfMonth.length;
}
//上个月
- (NSDate *)lastMonth:(NSDate *)date{
NSDateComponents *dateComponents = [[NSDateComponentsalloc] init];
dateComponents.month = -1;
NSDate *newDate = [[NSCalendarcurrentCalendar] dateByAddingComponents:dateComponentstoDate:date options:0];
return newDate;
}
//下个月
- (NSDate*)nextMonth:(NSDate *)date{
NSDateComponents *dateComponents = [[NSDateComponentsalloc] init];
dateComponents.month = +1;
NSDate *newDate = [[NSCalendarcurrentCalendar] dateByAddingComponents:dateComponentstoDate:date options:0];
return newDate;
}
//获取日
- (NSInteger)day:(NSDate *)date{
NSDateComponents *components = [[NSCalendarcurrentCalendar] components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay)fromDate:date];
return [components day];
}
//获取月
- (NSInteger)month:(NSDate *)date{
NSDateComponents *components = [[NSCalendarcurrentCalendar] components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay)fromDate:date];
return [components month];
}
//获取年
- (NSInteger)year:(NSDate *)date{
NSDateComponents *components = [[NSCalendarcurrentCalendar] components:(NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay)fromDate:date];
return [components year];
}