Take the 2-minute tour ×

I'm trying to use the NSDate dateFromString method but I'm getting an warning and it's crashing the app. The code looks like:

NSString *pickerDate = [NSString stringWithFormat:@"%@", timeSelector.date];
NSDate *defaultDate = [NSDate dateFromString:pickerDate];

The warning is:

'NSDate' may not respond to '+dateFromString'.

It appears that method is deprecated (in the midst of an upgrade from XCode 2 to 3.

What alternate method can I use to create a date from a string?

share|improve this question
I assume timeSelector is a UIDatePicker, is there a reason you're converting the date property to a string and back to a date again? –  dreamlax Aug 4 '10 at 3:54
That might be more efficient, just don't know what the code would be :/ Would you mind giving me an example? –  Ian McIntyre Silber Aug 4 '10 at 4:20
What I mean is, are you able to do just NSDate *defaultDate = timeSelector.date;? –  dreamlax Aug 4 '10 at 4:24

3 Answers 3

up vote 10 down vote accepted

NSDateFormatter is the intended way for you to get an NSDate from an NSString.

The most basic usage is something like this:

NSString *dateString = @"3-Aug-10";

dateFormatter.dateFormat = @"d-MMM-yy";

NSDate *date = [dateFormatter dateFromString:dateString];
share|improve this answer

I had a same problem. I changed the dateFormat from @"YYYY/M/d H:m:s" to @"YYYY/MM/dd HH:mm:ss" as follows. Then it works on my iPhone 4. (Xcode 4.5 for iOS 6.)

NSDateFormatter *dateFormatter1;
NSString *dateStr1=@"";
NSDate *gantanDate1;

dateFormatter1 = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter1 setLocale:[NSLocale systemLocale]]; 
[dateFormatter1 setTimeZone:[NSTimeZone systemTimeZone]]; 
dateFormatter1.dateFormat=@"YYYY/MM/dd HH:mm:ss";
dateStr1=@"2012/1/1 00:00:00"];
//  in his case,   dateStr1=pickerDate;  
gantanDate1 = [dateFormatter1 dateFromString:dateStr1];
share|improve this answer

Hi Silber everyone says the same thing to convert the string date to date object.Try this i think you have used two date formatters in two places where you are saving date to string and getting date from string.right try to use the same date formatters in both places. It will solve your problem.

share|improve this answer

Your Answer


