views:

19429

answers:

4

How do I convert an NSDate to an NSString so that only the year in @"yyyy" format is output to the string?

+6  A: 

You could do it with:

NSString *year = [myDate descriptionWithCalendarFormat:@"%Y" timeZone:nil locale:nil];

Note that you may not want to use the default time zone and locale, in which case you should specify them instead of passing nil. See the NSDate docs for more details.

mipadi
These dates are being read from a database and contain only a 4 digit year. I'm getting an uncaught exception when I try your code. Is my format throwing it off?
4thSpace
This works: NSString *startDate = [[NSString alloc] initWithFormat:(NSString *)dbStartDate];
4thSpace
+2  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
+15  A: 

How about...

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];

//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
Allan
This will produce a memory leak, since the formatter is never released.
mana
+3  A: 

Never forgetting the [formatter release] at the END!

CastroAPZ