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.
Tags: iphone-dev, NSDate, NSDateFormatter, NSString
not working ..!!
i tried this sample, m getting nil instead..
Yes working. As it is mentioned in comments your dateFormatter MUST match your dateString and if it doesn’t – you get nil instead of a nice NSDate. Set dateFormatter to something that matches your date (see link to Unicode Date Format Patterns) and try again.
Replace this code :
NSDate *dateFromString = [[NSDate alloc] init];
// ta-daaa!
dateFromString = [dateFormatter dateFromString:dateString];
by :
NSDate *dateFromString = [[dateFormatter dateFromString:dateString] retain];
…
…
[dateFromStrring release];
I think is better.
Bye