Converting string to date iOS

2019-09-21 12:33发布

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条回答
祖国的老花朵
2楼-- · 2019-09-21 12:48

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.

查看更多
登录 后发表回答