1.當(dāng)前月有多少天
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = range.length;
NSLog(@"%lu", (unsigned long)numberOfDaysInMonth);
2.獲取每月的第一天和最后一天
- (NSString *)getMonthBeginAndEndWith:(NSString *)dateStr{
? ? NSDateFormatter *format=[[NSDateFormatter alloc] init];
? ? [format setDateFormat:@"yyyy-MM"];
? ? NSDate *newDate=[format dateFromString:dateStr];
? ? double interval = 0;
? ? NSDate *beginDate = nil;
? ? NSDate *endDate = nil;
? ? NSCalendar *calendar = [NSCalendar currentCalendar];
? ? [calendar setFirstWeekday:2];//設(shè)定周一為周首日
? ? BOOL ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
? ? //分別修改為 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
? ? if (ok) {
? ? ? ? endDate = [beginDate dateByAddingTimeInterval:interval-1];
? ? }else {
? ? ? ? return @"";
? ? }
? ? NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
? ? [myDateFormatter setDateFormat:@"YYYY年MM月dd日"];
? ? NSString *beginString = [myDateFormatter stringFromDate:beginDate];
? ? NSString *endString = [myDateFormatter stringFromDate:endDate];
? ? NSString *s = [NSString stringWithFormat:@"%@-%@",beginString,endString];
? ? return s;
}
//調(diào)用格式(yyyy-MM)
NSString *dateStr = [self getMonthBeginAndEndWith:@"2019-10"];
3.月份是星期幾
- (NSDictionary *)weekdayStringWithDate:(NSDate *)date {
? ? //獲取星期幾
? ? NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSCalendarUnitWeekday fromDate:date];
? ? NSInteger weekday = [componets weekday];//1代表星期日,2代表星期一挑围,后面依次
? ? NSArray *weekArray = @[@{@"date":@"星期日",@"index":@"0"},@{@"date":@"星期一",@"index":@"1"},@{@"date":@"星期二",@"index":@"2"},@{@"date":@"星期三",@"index":@"3"},@{@"date":@"星期四",@"index":@"4"},@{@"date":@"星期五",@"index":@"5"},@{@"date":@"星期六",@"index":@"6"}];
? ? NSDictionary *weekDic = weekArray[weekday-1];
? ? return weekDic;
}
//傳入NSDate類型
NSDate *date1 = [self getDate:dateStringArray[0]];
NSDate *date2 = [self getDate:dateStringArray[1]];
NSString *weekStr = [self weekdayStringWithDate:date1][@"date"];
4.時(shí)間字符串轉(zhuǎn)NSDate
//時(shí)間字符串轉(zhuǎn)Date
- (NSDate *)getDate:(NSString *)dataStr{
? ? NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
? ? [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
? ? NSDate *date = [dateFormatter dateFromString:dataStr];
? ? return date;
}