简体   繁体   中英

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

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];

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM