
A short and simple recipe for getting an NSDate from an NSString using NSDateFormatter — the question behind it (“how do I parse a date string?”) is as current as ever, and the answer below is still the correct one on Apple platforms today.
NSString *dateString = @"2010-01-19"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // this is important - we set our input date format to match our input string // if the format doesn't match you'll get nil back, so be careful [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *dateFromString = [dateFormatter dateFromString:dateString]; // ta-daaa!
If you need more info about the different date formats, see the Unicode Date Format Patterns reference (this spec moves around — tr35-6 as originally linked is now tr35-dates). If you work with standard dates you can also use dateStyle/timeStyle instead of a custom dateFormat.
Notes for 2026
- The two-line cleanup above matters: the original snippet allocated an NSDate and then immediately leaked it by overwriting the pointer with the formatter’s return value. NSDateFormatter returns an autoreleased object under MRC and you don’t own it — under ARC it’s a non-issue, but the overwrite was still wrong.
setDateFormatthrows an exception if you pass nil or an empty string, and a parse silently returns nil on any mismatch — which is exactly the trap the original comment warned about.- Don’t do this on a hot path. NSDateFormatter creation is expensive; create one formatter and reuse it (or use the ISO 8601 specialist,
NSISO8601DateFormatter, added in iOS 10 / macOS 10.12). - Never parse with a user-visible locale. Set
locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]for fixed-format parsing, otherwise users on non-Gregorian calendars get nil or wrong dates. - In Swift the same job is
DateFormatterwithdateFormat = "yyyy-MM-dd"anddate(from:)— see DateFormatter in Apple’s docs. Apple’s old NSDateFormatter class-reference page now redirects there.