19

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.

Michael Morrison
  • 1,323
  • 1
  • 18
  • 30
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168

4 Answers4

91
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); 
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
situee
  • 2,710
  • 2
  • 22
  • 27
  • 8
    For locale reasons, you shouldn't set the date & time formats explicitly. Instead, use the locale-friendly styles: `[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];` – Graham Perks Feb 27 '12 at 04:08
  • 1
    @GrahamPerks that's not always true. What if, for example, you're generating a date to send to a web api which will need to be parsed by the server? – Will Pragnell Mar 06 '12 at 12:27
  • 1
    Fair enough. I'm pointing out not to blindly copy the code in the answer; if the string is going to be seen by a user, it needs a tweak. – Graham Perks Mar 07 '12 at 04:42
  • 1
    Then I'll add my 2 cents as well. Most users do not know how to change system date formats, and a lot of apps do not respect them, so just because the system has a certain format, doesn't mean the user likes it or it is good to use. Just my experience after 10+ years in the GUI design business. – eselk Oct 10 '12 at 18:50
32

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.

Sebastian Celis
  • 12,185
  • 6
  • 36
  • 44
10

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.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
1

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
  • 31,139
  • 18
  • 86
  • 102