iOS日期

今天用到了日期,来写一写代码:
//日期的当天是几号
-(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分别对应周一-周六

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容