我想计算两个 NSDate 之间的月数和天数。我可以正确计算天数,但如何将其转换为月数和剩余天数?
这就是我用来计算总天数的方法,它工作正常。
- (NSInteger) numberOfDaysUntil {
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[self dateOnly:[NSDate date]]];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[self dateOnly:self]];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
最佳答案
作为Hot Licks正确地说,在大多数日历中,您不能将天数转换为月/天。
但是,如果您同意 Apple 的实现,NSCalendar
方法 components:fromDate:toDate:options:
可以执行此计算。来自文档:
The result is lossy if there is not a small enough unit requested to hold the full precision of the difference. Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.
文档中的讨论甚至包括针对您的问题的示例代码:
NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
int days = [comps day];
关于objective-c - 两个 NSDate 之间的月数和天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654741/