objective-c - 两个 NSDate 之间的月数和天数

标签 objective-c ios nsdate

我想计算两个 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/

相关文章:

objective-c - NSPredicate 中的减法

objective-c - 在 Cocoa 应用程序中处理 Cmd-Q(以编程方式处理菜单项 'Quit Application')

iOS 6 无法检查仅包含字母数字字符的字符串

iphone - 无障碍焦点

ios - Material 组件选项卡栏 Controller 错误

ios - 使用 Swift 从字符串中检测数字年份

ios - 跨越新年时获取两个 NSDate 之间的天数

ios - BST 的 NSDateFormatter 而不是 GMT+1

ios - CMSampleBufferRef 池写入 H.264 AVCC 流

iphone - 这个控件在 UIKit 中可用吗?