两个 NSDates 之间的月数和天数 [英] Number of Months and Days between two NSDates

查看:42
本文介绍了两个 NSDates 之间的月数和天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算两个 NSDates 之间的月数和天数.我的天数计算正确,但如何将其转换为月份和剩余天数?

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

推荐答案

正如 Hot Licks 正确说的,你在大多数日历中无法将天数转换为月/天.

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

但是,如果您同意 Apple 的实现,NSCalendar 方法 components:fromDate:toDate:options: 可以执行此计算.来自文档:

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

如果没有足够小的单位要求保持差异的完整精度,则结果是有损的.有些操作可能不明确,计算行为是特定于日历的,但通常较大的组件会在较小的组件之前计算;例如,在公历中,结果可能是 1 个月零 5 天,而不是例如 0 个月零 35 天.

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

这篇关于两个 NSDates 之间的月数和天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆