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
2009-02-23 01:24:21
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
2009-02-23 01:51:29
This works: NSString *startDate = [[NSString alloc] initWithFormat:(NSString *)dbStartDate];
4thSpace
2009-02-23 01:55:13
+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
2009-04-23 20:47:37
+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
2009-05-30 22:38:51