iOS日历时间相关整理
1.当前月有多少天
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];//设定周一为周首日
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;
}
//调用格式(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.时间字符串转NSDate
//时间字符串转Date
- (NSDate *)getDate:(NSString *)dataStr{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
NSDate *date = [dateFormatter dateFromString:dataStr];
return date;
}