Leon
Leon

Reputation: 410

Get start date from week number

I've been trying and searching for over two days now.

The only thing I'm trying is to convert a week number "Week 50" to the start date of the week.

I've tried to convert with dateFromString like this:

        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"w"];
        NSDate *date = [dateFormat dateFromString:dateStr]; 
        NSLog(@"date(%@)", date);
        NSDateFormatter *formatting = [[NSDateFormatter alloc] init];
        [formatting setDateFormat:@"YYYY/MM/dd"];
        NSString *stringDate = [formatting stringFromDate:date];
        NSLog(@"date: %@", stringDate);
        [dateFormat release];

But both objects return (null) so it isn't of many help.

Regards

Upvotes: 0

Views: 787

Answers (2)

V1ru8
V1ru8

Reputation: 6147

Have you tried the following:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2012];
[comps setWeek:50];

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *week50 = [cal dateFromComponents:comps];

Upvotes: 5

Michał Zygar
Michał Zygar

Reputation: 4092

You can try trimming the string to just the week number like "50" and then add the desired year number and use following:

NSString *dateStr=@"50 2011";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"w YYYY"];
NSDate *date = [dateFormat dateFromString:dateStr]; 
NSLog(@"date(%@)", date);

Upvotes: 0

Related Questions