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分別對應周一-周六

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容