今天用到了日期,来写一写代码:
//日期的当天是几号
-(NSInteger )dayInDate:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components day];
}
//日期的月份
-(NSInteger )monthInDate:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components month];
}
//日期的年份
-(NSInteger )yearInDate:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components year];
}
//每月有多少天
-(NSInteger )totaldaysInMonthOfDate:(NSDate *)date{
NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
return totaldaysInMonth.length;
}
//以今天为准,上/本/下月的今天
-(NSDate *)lastMonthOfDate:(NSDate *)date{
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.month = -1;
//-1上一个月
//0本月
//1下一个月
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
return newDate;
}
//某个月的第一天是周几
-(NSInteger )firstWeekdayInThisMonth:(NSDate *)date{
NSCalendar *calendar = [NSCalendar currentCalendar];
//设置每周的第一天的值 1对应周日(默认)
[calendar setFirstWeekday:1];//Sun:1,Mon:2,Thes:3,Wed:4,Thur:5,Fri:6,Sat:7
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
[components setDay:1];
NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonth];
return firstWeekday - 1;//减1之前:1对应周日,2对应周一,...,7对应周六;减1后变为:0对应周日,1-6分别对应周一-周六
}