user4407163
user4407163

Reputation: 1

NSCalendar NSDateComponents weekofYear return 1 with date 2014-12-31

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?

Upvotes: 0

Views: 1041

Answers (3)

gnasher729
gnasher729

Reputation: 52530

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.

Upvotes: 0

dreamlax
dreamlax

Reputation: 95325

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

Upvotes: 1

dreamlax
dreamlax

Reputation: 95325

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

Upvotes: 0

Related Questions