Converting string to date iOS

2019-09-21 13:00发布

问题:

I have the following string:

01/27/2016 11:00:00

And I am passing it to this method:

-(NSDate*)dateFromString:(NSString*)dateString format:(NSString*)format {
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"MM/dd/yy, HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

    NSLog(@"%@", [dateFormatter dateFromString:strToConvert]);
}

and it is returning nil. Not sure what I am doing wrong here.

Edit:This only seems to be happening on the iPhone, on the iPad it functions fine.

回答1:

Try this.

-(NSDate*)dateFromString:(NSString*)dateString format:(NSString*)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"]; //01/27/2016 11:00:00
    NSDate *date = [dateFormatter dateFromString:dateString];
    return date;
}

Your code missing returning statement. I hope you would getting an error too.