如何计算目标C中今年的天数 [英] How do I calculate the number of days in this year in Objective C
问题描述
如何计算任何日历的一年中的天数,而不仅仅是格里高利。
我试过这个
How can i calculate the number of days in a year for any calendar, not just gregorian. I have tried this
NSUInteger * days = [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date] ];
但是这给了我当月的天数而不是当年的天数。
but that gives me the number of days in the current month instead of the number of days in the current year.
推荐答案
我终于想出了一个有效的解决方案。我所做的是首先计算一年中的月数,然后计算每个月的月数。
I finally came up with a solution that works. What I do is first calculate the number of months in the year and then for each month calculate the number of days for that month.
代码如下所示:
NSUInteger days = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];
NSUInteger months = [calendar rangeOfUnit:NSMonthCalendarUnit
inUnit:NSYearCalendarUnit
forDate:today].length;
for (int i = 1; i <= months; i++) {
components.month = i;
NSDate *month = [calendar dateFromComponents:components];
days += [calendar rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:month].length;
}
return days;
它不像我希望的那样整洁,但它适用于任何日历,例如普通的格里高利人或伊斯兰人。
It is not as neat as I would have hoped for but it will work for any calendar such as the ordinary gregorian one or the islamic one.
这篇关于如何计算目标C中今年的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!