views:

5055

answers:

4

Hi, I have the following code:

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

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

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

What am I doing wrong?

Thank you in advance.

+11  A: 

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.

Sebastian Celis
+1  A: 

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.

pix0r
I'm assuming this is standard Cocoa as descriptionWithLocale does not exist on the iPhone, either.
Sebastian Celis
Good point. I did see another similar question that was iphone-related, so I think I'll re-post this response there.
pix0r
+6  A: 

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

Mike Abdullah
+2  A: 
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(dateString); 
y.situ