简体   繁体   中英

How can I Convert a NSString to a valid NSDate (iOS)

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?

正确的方法是将NSDateFormatter用作从字符串创建日期的工厂(反之亦然)。

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.

Try:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss Z";
NSDate *notificationDate = [formatter dateFromString:firingDate];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM