0

How can I calculate the date having only the week number and day of the week?

E.g. Week 24, Tuesday, 2012, where weeks start on Monday.

jscs
  • 63,694
  • 13
  • 151
  • 195
Oleg
  • 2,984
  • 8
  • 43
  • 71
  • this might give you a pointer http://stackoverflow.com/questions/2466022/how-to-find-weekday-from-todays-date-in-iphone-sdk – geminiCoder Jun 13 '12 at 07:20

2 Answers2

1

Very conveniently, NSCalendar will do all the math for you. First, set up the parameters using NSDateComponents:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setWeek:24];
[comps setWeekday:3]; //map weekday names to numbers (e.g., Sunday is 1)
[comps setYear:2012];

Then create a Gregorian calendar with those date components:

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

And grab your NSDate:

 NSDate *date = [gregorian dateFromComponents:comps];
Adam Leonard
  • 489
  • 2
  • 5
  • 1
    As I wrote above your solution works fine! But now I have another problem - it detects date for a previous day: 2012-06-11 22:00:00 +0000 instead of 2012-06-12 00:00:00. I assume it is something related to TimeZones. All my dates should be in GMT+2 timezone. Can you help with that? – Oleg Jun 13 '12 at 07:56
  • 1
    Good question. Dealing with time zones is tricky and dependent on what you want to do, but if you don't care about the time and just want the date, I think one easy and safe workaround is to work in GMT (+0000). To do that, add this line before you grab the date: `[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];`. That works for me, but someone else might have a better answer. – Adam Leonard Jun 13 '12 at 08:33
0
    NSDate *now = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
    [comp setWeek:24];
    [comp setDay:1]; 
    NSDate *resultDate = [gregorian dateFromComponents:comp];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM d, yyyy"];


    NSString *myDateString = [formatter stringFromDate:resultDate];

    [gregorian release]; // Clean up allocated objects by releasing them
    [formatter release];

    NSString * date = [NSString stringWithFormat:@"Week of %@", myDateString];
Krunal
  • 6,440
  • 21
  • 91
  • 155
Prabha
  • 424
  • 1
  • 4
  • 11