Question

In my iOS app I have to create a week based on the current date.

This is the piece of code:

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setWeek:week];
[components setWeekday:2];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:components];

In this particular case the year is 2012 and the week is 1. I would expect the calendar to return 2012-01-02, as that is the date of monday in week 1 / 2012. But instead it returns 2012-12-30.

UPDATED with Timezone:

NSDateComponents *components = [[NSDateComponents alloc] init];    
[components setYear:2012];
[components setWeek:1];
[components setWeekday:2];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [gregorian dateFromComponents:components];

Still returns 2012-12-30.

Était-ce utile?

La solution

I found out that this code behaves as you expect

[components setYearForWeekOfYear:year];
[components setWeekOfYear:week];
[components setWeekday:2];

It looks legit but the document does not say much so use it at your own risk. ^ ^

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top