最近刽酱,公司項(xiàng)目中用到了日歷,于是打算自己寫(xiě)一下瞧捌,下面做一下總結(jié)棵里。
要想實(shí)現(xiàn)日歷,首先需要知道一個(gè)月有多少天姐呐,再需要知道每月第一天是周幾衍慎,其他的也就能根據(jù)這兩點(diǎn)計(jì)算出來(lái)了。
廢話(huà)不多說(shuō)皮钠,來(lái)看關(guān)鍵代碼??
1.初始化
NSCalendar多次初始化可能會(huì)造成性能較低稳捆,避免多次初始化,建議定義為全局變量麦轰。
//指定日歷的算法
self.calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
2.獲取當(dāng)月天數(shù)
傳入要計(jì)算的日期乔夯,以月為單位計(jì)算。
/**
獲取當(dāng)月的天數(shù)
*/
-(NSInteger)getNumberOfDaysInMonthWith:(NSDate*)date
{
NSRange range = [_calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
return range.length;
}
3.獲取一個(gè)月中的每一天是周幾
1:周日 2:周一 3:周二 4:以此類(lèi)推
/**
獲取每一天是周幾
*/
-(id)weekdayOfMonthWith:(NSDate*)date
{
NSDateComponents *comps = [_calendar components:NSCalendarUnitWeekday fromDate:date];
//1:周日 2:周一 3:以此類(lèi)推
return @([comps weekday]);
}
4.計(jì)算每月一號(hào)是周幾
/**
每月一號(hào)是周幾
*/
-(NSInteger)firstdayWeekOfMonth:(NSDate*)date
{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
NSDate *currentDate = date;
[formatter setDateFormat:@"yyyy-MM"];
NSString * str = [formatter stringFromDate:currentDate];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *sr = [NSString stringWithFormat:@"%@-1",str];
NSDate *suDate = [formatter dateFromString:sr];
NSInteger firstDay = [[self weekdayOfMonthWith:suDate] integerValue];//每月一號(hào)是周幾
return firstDay;
}
5.計(jì)算每月日歷顯示的行數(shù)
/**
獲取一個(gè)月的行數(shù)(周數(shù))
*/
-(NSInteger)rowsOfMonthWith:(NSDate*)date
{
NSInteger dayCount = [self numberOfDaysInMonthWith:date]; //一個(gè)月的總天數(shù)
NSInteger firstDay = [self firstdayWeekOfMonth:date]; //一個(gè)月的第一天是周幾
NSInteger rows = (dayCount - (8 - firstDay)) / 7 + 1;
return (dayCount - (8 - firstDay)) % 7 > 0 ? rows + 1 : rows;
}
6.NSDate和NSDateComponents之間的轉(zhuǎn)換
#pragma mark - 轉(zhuǎn)換方法
-(NSDateComponents *)dateToComponents:(NSDate*)date
{
NSDateComponents *components = [_calendar components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
return components;
}
-(NSDate *)componentsToDate:(NSDateComponents*)components
{
components.hour = 0;
components.minute = 0;
components.second = 0;
NSDate *date = [_calendar dateFromComponents:components];
return date;
}