在iOS中获取错误的周数

时间:2012-07-25 11:34:37

标签: objective-c ios5 nsdate nsdateformatter nscalendar

我想在iPhone上获得周数。我正在使用这段代码

NSNumber* getWeek() {
    NSDate *currDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"w.ee"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    NSNumberFormatter *weekNumber = [[NSNumberFormatter alloc] init];
    [weekNumber setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *week = [weekNumber numberFromString:dateString];
    [weekNumber release];
    return week;
 }

然而,我有不同的结果,在模拟器上没问题,但是当我在iPhone中运行时这让我“0” IOS 5.0.1

有帮助吗?

1 个答案:

答案 0 :(得分:2)

使用字符串表示周数不是获取此类信息的最佳方式。 NSCalendarNSDateComponents专为此类计算而设计:

NSDate *currDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSWeekOfYearCalendarUnit|NSWeekdayCalendarUnit fromDate:currDate];
NSLog(@"%d %d", components.weekOfYear, components.weekday);

您可以在日历调用中指定组件列表(第3行),如示例说明中所示,只保证在NSDateComponents对象中填充指定的组件。