NSDateComponents: difference between weekOfYear and weekOfMonth

In my application, I need to set up a weekly reminder so that the notification goes off the same day / time, after a week. I use NSDateComponenents.week = 1 and add this to NSDate using the NSCalendar API dateByAddingComponents:toDate:options: It seems that week now deprecated in iOS7, and the warning tells me: "Use weekOfMonth or weekOfYear, depending on what you mean." But I can not find a lot of documentation on what of them means.

Can anyone explain the difference between the two? In a basic test, two return the same value when added to NSDate, but I'm sure there is a significant difference between them.

+7
objective-c cocoa-touch cocoa nsdate nsdatecomponents
source share
3 answers

The difference between the two impressions shows the week relative to the month or year.

The second week (weekOfMonth) of February will be the seventh week (weekOfYear) of the year, for example, depending on the year.

Regarding the use of date components to add weeks to a date, this does not seem to matter which is used, but weekOfYear seems preferable on the Internet.

I did some testing on the Swift playground, and they always calculated the same value when adding weeks to the date.

weekOfMonth vs weekOfYear

+5
source share

I have always found that weeks seem to be handled weirdly in iOS.

weekOfMonth will be 1, 2, 3, 4, etc.

weekOfYear will be from 1 to 52 (I think)

They are apparently not measures of duration. Just like โ€œApril 3โ€ is not a measurement of duration, while โ€œ1 dayโ€ is a measurement of duration.

The best way to add one week is ...

 NSCalendar *calendar = [NSCalendar currentCalendar]; NSDate *currentDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:7]; NSDate *date = [calendar dateByAddingComponents:comps toDate:currentDate options:0]; 

EDIT

After a little test, I was right.

 NSDate *date = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comps = [calendar components:NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear fromDate:date]; Printing description of date: 2014-08-20 08:15:13 +0000 Printing description of comps: <NSDateComponents: 0xb7753c0> Week of Year: 34 Week of Month: 4 
+4
source share

The difference is useful if you want the event to always turn on, for example, on the second Tuesday of the month.

In this case, you want weekOfMonth to be 2.

+2
source share

All Articles