【问题标题】:Wrong year set when converting NSDate to NSString将 NSDate 转换为 NSString 时设置错误的年份
【发布时间】:2012-05-09 15:59:59
【问题描述】:

我正在尝试以这种方式使用 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 年????

附言。我已经检查了NSDate returns wrong year,但我没有使用日本日历。

非常感谢

【问题讨论】:

  • 你需要把NSLocal改成NSLocale

标签: string date nsdate


【解决方案1】:

试试这个:

     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多年都不是UDF,所以必须使用yyyy。
猜你喜欢
  • 2017-11-10
  • 2014-12-06
  • 1970-01-01
  • 2019-07-30
  • 2016-09-01
  • 2016-09-21
  • 1970-01-01
  • 2011-04-24
  • 2017-04-23
相关资源
最近更新 更多