NSDate from NSString gives null result

我的梦境 提交于 2019-12-01 14:16:01

As Narayana suggested you need to retrieve the date with same format as you have stored. Retrieve it as below : -

    NSDateFormatter *reDateFormatter = [[NSDateFormatter alloc] init];
    [reDateFormatter setDateFormat:@"dd-MM-yyyy hh:MM:SS a"];
    [reDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *dt = [reDateFormatter dateFromString:str];
    NSLog(@"The Date : %@",dt);

    [reDateFormatter setDateFormat:@"hh:MM:SS a"];
    NSString *currentTime = [reDateFormatter stringFromDate:dt];
    NSLog(@"%@",currentTime);

Hope it helps you.

First off, why not just store the NSDate object or epoch timestamp? This will give you much more flexibility in the future.

Now to your problem, I suspect it is due to your configuration of the NSDateFormatter, you're saving it in one format and trying to convert it to a date using a different format. Make the formats the same and try again. If you want to display it differently than it is stored you're likely going to need to convert it to and NSDate using the stored format and then again use another date formatter to get it in the format you want it as a string.

Try to format it to dd-MM-yyyy hh:mm:ss a.

You wrote dd-MM-yyyy hh:MM:SS a where MM in hh:MM:SS gives month which is unrecognized in this format and there is no point writing upercase SS for seconds

Hope you understand it.

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