将NSDate转换为NSString时设置错误的年份

时间:2012-05-09 15:59:59

标签: string date nsdate

我正在尝试以这种方式使用NSDate类别生成字符串:

NSString* dateString = nil;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocal currentLocale]];
[dateFormat setDateFormat:@"dd LLL YYYY"];
dateString = [dateFormat stringFromDate:self];
return dateString;

转换工作正常,但在一种情况下(我报告调试会话): 如果我尝试转换这样的NSDate对象:

(gdb) po self
2012-01-01 00:00:00 +0000

我获得:

(gdb) po dateString
01 Jan 2011

为什么这一年会回到2011年????

PS。我已经检查了NSDate returns wrong year而我没有使用日历。

非常感谢

1 个答案:

答案 0 :(得分:2)

试试这个:

     NSDate *pickerDate = [NSDate date];
     NSCalendar*       calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
     NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
        components.day = 0; //This value to take from today to next 1 or 2 or 3 days
        NSDate* newDate = [calendar dateByAddingComponents: components toDate: pickerDate options: 0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MMMM"];
        NSString *textDate = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:newDate]];
        [dateFormatter release];