Number of Months and Days between two NSDates

家住魔仙堡 提交于 2020-01-01 17:08:36

问题


I would like to calculate the number of months and days between two NSDates. I have the number of days calculating correctly, but how can convert that to months and remainder days?

This is what I'm using to calculate total number of days, which is working correctly.

- (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];
}

回答1:


As Hot Licks correctly said, you can't convert a number of days to months/days in most calendars.

However, the NSCalendar method components:fromDate:toDate:options: can do this calculation if you agree with Apple's implementation. From the documentation:

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.

The discussion in the documentation even includes sample code for exactly your problem:

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];


来源:https://stackoverflow.com/questions/11654741/number-of-months-and-days-between-two-nsdates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!