How do I calculate the number of days in this year in Objective C

前端 未结 12 2122
旧巷少年郎
旧巷少年郎 2020-12-06 03:07

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

12条回答
  •  爱一瞬间的悲伤
    2020-12-06 04:04

    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.

    The code looks like this:

    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.

提交回复
热议问题