iOS 计算两个日期之间的天数问题

时间:2023-03-08 16:02:44
iOS 计算两个日期之间的天数问题
 //获取当前时间若干年、月、日之后的时间
+ (NSDate *)dateWithFromDate:(NSDate *)date years:(NSInteger)years months:(NSInteger)months days:(NSInteger)days{
NSDate * latterDate;
if (date) {
latterDate = date;
}else{
latterDate = [NSDate date];
}
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
fromDate:latterDate]; [comps setYear:years];
[comps setMonth:months];
[comps setDay:days]; return [calendar dateByAddingComponents:comps toDate:latterDate options:];
}
 /**
* @method
*
* @brief 获取两个日期之间的天数
* @param fromDate 起始日期
* @param toDate 终止日期
* @return 总天数
*/
+ (NSInteger)numberOfDaysWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents * comp = [calendar components:NSCalendarUnitDay
fromDate:fromDate
toDate:toDate
options:NSCalendarWrapComponents];
NSLog(@" -- >> comp : %@ << --",comp);
return comp.day;
}

根据以上两个方法可以获得更多根据日期计算天数的方法,只是在获取日期时传的参数不同,在此就不一一列举了。