Tag Archives: NSString

Getting NSDate from NSString

Very useful, yet short and simple, code snippet on how to rip the NSDate from NSString using NSDateFormatter:

NSString *dateString = @"2010-01-19";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
// ta-daaa!
dateFromString = [dateFormatter dateFromString:dateString];

If you need more info about different date formats see Unicode Date Format Patterns. Of course if you usually work with standard dates you can use setDateStyle instead of setDateFormat.