问题
I want to get weekofYear with date '2014-12-31' ,but it always return 1 not 52 here is my code:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
NSlog(@"%i",dateComponent.weekOfYear);
output "1";
I know result is right, but I want get "52" not '1',how to fix it?
回答1:
An alternative approach is to use the yearForWeekOfYear
property of the NSDateComponents
instance. If the yearForWeekOfYear
is after the year of the date passed to components:fromDate:
, then it is week 52.
E.g.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSYearForWeekOfYearCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
NSInteger weekOfYear = dateComponent.weekOfYear;
if (dateComponent.yearForWeekOfYear > dateComponent.year)
weekOfYear = 52;
NSLog(@"%i",weekOfYear); // 52
回答2:
Set the minimumDaysInFirstWeek property of the NSCalendar
instance before obtaining the date components.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.minimumDaysInFirstWeek = 7; // the week has to be completely within one year
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
NSLog(@"%i",dateComponent.weekOfYear); // 52
回答3:
IF the week is 1 (first days of 2015 or last few days of 2014)
AND the day is greater than 20 (so it's one of the last three days of 2014)
THEN (calculate the week of your date minus 5 days, and add 1).
This will make the last few days of the year into their own week, which is sometimes week 52, sometimes week 53. And it works with European and US calendars.
You'll need to think what you want to do if Jan 1st is in the last week of the previous year. Might make it week 0. So really going with the standard and accepting what iOS tells you is the saner way to do it.
来源:https://stackoverflow.com/questions/27715711/nscalendar-nsdatecomponents-weekofyear-return-1-with-date-2014-12-31