0

I'm passing a string from javascript to Objective-C in the form of "2012-02-17 14:21:30 +0000". My code is as follows:

NSString *firingDate = [_parameters objectForKey:@"fire"];
NSDate *notificationDate = [NSDate dateWithString:firingDate];

The issue is that I ended up reading the OS X reference instead of the iOS docs (doh!) so this throws a warning as dateWithString isn't present in iOS. In theory I suppose that this shouldn't work at all but it does, albeit with that warning.

What is the Correct way to convert the string to a NSDate?

Finne
  • 150
  • 3
  • 8
  • possible duplicate of [NSString to NSDate](http://stackoverflow.com/questions/1353081/nsstring-to-nsdate) – DarkDust Feb 17 '12 at 15:02

3 Answers3

3

The correct way is to use NSDateFormatter as a factory to create dates from strings (and vice versa).

fzwo
  • 9,842
  • 3
  • 37
  • 57
2

Try this:

NSString *firingDate = [_parameters objectForKey:@"fire"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *notificationDate = [dateFormatter dateFromString:firingDate];

Check out the reference for parsing dates from multiple regions.

Don't forget to release your formatter when finished.

Costique
  • 23,712
  • 4
  • 76
  • 79
Destron
  • 414
  • 2
  • 9
2

Try:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss Z";
NSDate *notificationDate = [formatter dateFromString:firingDate];
sch
  • 27,436
  • 3
  • 68
  • 83