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.
Just 3 steps. NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init]; Set the date format in which you want your string. NSDate *date = [NSDate date]; // your NSDate object NSString *dateString = [dateFormatter stringFromDate:date];
The most common operation when using date ( NSDate) objects in applications, is to convert them into string objects so they can be properly formatted and shown to the users. Quite common is the reverse action as well; converting strings to date objects. However, these are not the only tasks regarding dates.
Let’s see now the first method for comparing dates. In case you want to determine the earlier or the later between two dates, then the NSDate class can help you a lot towards this effort as it provides two methods named earlierDate: and laterDate: respectively. The syntax when using any of those methods is simple:
If by looking at the “2000-01-01” date in the above results you become curious or suspicious, then don’t worry. The NSDate adds this by default when no specific date is given for conversion, and it doesn’t interfere by any means to the rest of the date parts (in this case the time).
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);
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With