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

前端 未结 12 2123
旧巷少年郎
旧巷少年郎 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 03:56

    I don't know if anybody is still interested in this thread, but is another possible solution:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *startOfYear;
    NSTimeInterval lengthOfYear;
    [calendar rangeOfUnit:NSYearCalendarUnit
                startDate:&startOfYear
                 interval:&lengthOfYear
                  forDate:[NSDate date]];
    NSDate *endOfYear = [startOfYear dateByAddingTimeInterval:lengthOfYear];
    NSDateComponents *comp = [calendar components:NSDayCalendarUnit
                                         fromDate:startOfYear
                                           toDate:endOfYear
                                          options:0];
    NSUInteger numberOfDaysInThisYear = [comp day];
    

    using only 2 calls to NSCalendar.

提交回复
热议问题