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

标签 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;

转换工作正常,除了一种情况(我报告调试 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/

相关文章:

c++ - 无法从 stringstream 解析数字并正确输出它们 C++

r - 更改日期变量中的行值

java - 尝试获取“EEEE MMM d, yyyy”格式的日期时,返回当前日期的无效值

php - 如何获取上月和下月?

iOS 将日期转换为字符串 AM/PM

swift - 在顶部 TableView 中对降序排列的日期进行排序

objective-c - iOS 开发 : timeIntervalSince1970 not updating when in a NSRunLoop

c - 交换字符串数组中的元素

Java - 从字符串中删除\u0000

C:在这种情况下,字符串的行为如何?