我试图以这种方式使用 NSDate 类别生成一个字符串:
NSString* dateString = nil;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocal currentLocale]];
[dateFormat setDateFormat:@"dd LLL YYYY"];
dateString = [dateFormat stringFromDate:self];
return dateString;
转换工作正常,除了一种情况(我报告调试 session ): 如果我尝试像这样转换 NSDate 对象:
(gdb) po self
2012-01-01 00:00:00 +0000
我得到:
(gdb) po dateString
01 Jan 2011
为什么年份要回溯到2011年???
PS。我已经查过NSDate returns wrong year而且我没有使用日本日历。非常感谢
最佳答案
试试这个:
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];
关于string - 将 NSDate 转换为 NSString 时设置了错误的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10519743/