String description of NSDate

偶尔善良 提交于 2019-12-03 03:49:01

问题


I have the following code:

[ [NSDate date] descriptionWithLocale: @"yyyy-MM-dd" ]

I want it to return a date in the following format: "2009-04-23"

But it returns: Thursday, April 23, 2009 11:27:03 PM GMT+03:00

What am I doing wrong?

Thank you in advance.


回答1:


You are using the wrong method. Instead try descriptionWithCalendarFormat:timeZone:locale:

[[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d"
                                    timezone:nil
                                      locale:nil];

Also note that the method is expecting a different format than the one in your question. The full documentation for that can be found here.

EDIT: Though as Mike noted, you really should be using NSDateFormatter. There are some problems with descriptionWithCalendarFormat:timezone:locale: that Apple mentions in the documentation.




回答2:


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); 



回答3:


Also note that for most cases, NSDateFormatter is to be preferred for its flexibility.

There's also a significant performance benefit to be had from re-use of date formatters in many apps.




回答4:


If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale: available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings. You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970.



来源:https://stackoverflow.com/questions/783395/string-description-of-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!