Reputation: 150
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?
Upvotes: 0
Views: 399
Reputation: 27506
Try:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss Z";
NSDate *notificationDate = [formatter dateFromString:firingDate];
Upvotes: 2
Reputation: 404
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.
Upvotes: 2
Reputation: 9902
The correct way is to use NSDateFormatter
as a factory to create dates from strings (and vice versa).
Upvotes: 3