0

如何计算只有星期数和星期几的日期?

例如,第 24 周,星期二,2012,星期从星期一开始。

4

2 回答 2

1

非常方便,NSCalendar 会为你做所有的数学计算。首先,使用 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];

然后使用这些日期组件创建一个公历:

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

并抓住你的 NSDate:

 NSDate *date = [gregorian dateFromComponents:comps];
于 2012-06-13T07:20:51.250 回答
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];
于 2012-06-13T07:18:36.947 回答