Number of weeks in month

2019-02-21 05:39发布

问题:

I have the following code:

NSDate *dateNow = [[NSDate alloc] init];
NSTimeInterval timeDifference = [usersDate timeIntervalSinceDate:dateNow];
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:timeDifference sinceDate:date1]; 

// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSWeekCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSSecondCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

NSLog(@"Break down: %d Years, %d months, %d Weeks, %d days %d Hours, %d Minutes, %d Seconds", [breakdownInfo year], [breakdownInfo month], [breakdownInfo week], [breakdownInfo day], [breakdownInfo hour], [breakdownInfo minute], [breakdownInfo second]);

It prints output such as:

Break down: 0 Years, 5 months, 3 Weeks, 4 days 2 Hours, 48 Minutes, 20 Seconds

I actually do not need the number of months until the date, but the total of the number of weeks, is there anyway I can modify the code to do this? I do not want to simply assume that 1 month = 4 weeks as this would undoubtably be wrong.

Kind Regards

回答1:

Doesn't it work to just use:

unsigned int unitFlags = NSWeekCalendarUnit;

?