题
我有以下代码:
[ [NSDate date] descriptionWithLocale: @"yyyy-MM-dd" ]
我希望它返回以下格式的日期:"2009-04-23"
但它返回:2009 年 4 月 23 日星期四晚上 11:27:03 GMT+03:00
我究竟做错了什么?
先感谢您。
解决方案
您使用了错误的方法。相反尝试 descriptionWithCalendarFormat:timeZone:locale:
[[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d"
timezone:nil
locale:nil];
另请注意,该方法需要与您问题中的格式不同的格式。可以找到完整的文档 这里.
编辑:尽管正如迈克指出的,你确实应该使用 NSDateFormatter
. 。有一些问题 descriptionWithCalendarFormat:timezone:locale:
苹果在文档中提到的。
其他提示
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release]; // delete this line if your project uses ARC
NSLog(@"%@",dateString);
另外请注意,在大多数情况下,NSDateFormatter
是优选为它的灵活性。
有也将在许多应用程序重复使用日期格式化的有显著的性能优势。
如果你没有可用NSDate -descriptionWithCalendarFormat:timeZone:locale:
(我不相信iPhone /可可触摸包含本),您可能需要使用的 strftime的周围一些C风格字符串和猴子。你可以从一个NSDate使用NSDate -timeIntervalSince1970
的UNIX时间戳。
不隶属于 StackOverflow