将NSDate转换为NSString时设置了错误的年份
我试图通过以下方式使用NSDate类别生成字符串:将NSDate转换为NSString时设置了错误的年份,string,date,nsdate,String,Date,Nsdate,我试图通过以下方式使用NSDate类别生成字符串: NSString* dateString = nil; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setLocale:[NSLocal currentLocale]]; [dateFormat setDateFormat:@"dd LLL YYYY"]; dateString = [dateFormat stringFromDate:sel
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年
另外,我已经检查过了,我没有使用日式日历
非常感谢试试这个:
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];
事实上,我可能已经找到了一个更简单的解决方案..在日期格式中,用YYYY替换YYYY您能确认它也适用于您吗?是的,这是所有日期元素的通用日期格式:setDateFormat:@“yyyy'-'MM'-'dd''HH':'MM':'ss'->MM月MM分钟yyyy年等等:)因为yyyy多年来都不是自定义项,所以必须使用yyyy。您需要将
NSLocal
更改为NSLocale
。