Converting string to date iOS

你说的曾经没有我的故事 提交于 2019-12-13 08:02:39

问题


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.



来源:https://stackoverflow.com/questions/39041329/converting-string-to-date-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!