NSDate from NSString gives null result

自作多情 提交于 2019-12-19 12:53:09

问题


I am using following code to generate NSDate -> NSString

+(NSString *)getCurrentTime
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy hh:MM:SS a"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString* str =[dateFormatter stringFromDate:now];
    [dateFormatter release];
    NSLog(@"%@",str);
    return str;
}

everything is fine in above code. I am using above code to store string in Database. Now while retrieving that string gives me NULL. Following is my code to retrieve date in specific format

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:MM:SS a"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *dt =[dateFormatter dateFromString:crdInfo.swipeTime];
    NSLog(@"Date : %@",dt);
    [dateFormatter release];

How should I retrieve or store with particular format?? My crdInfo.swipeTime is retrieving String propertly...


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8396796/nsdate-from-nsstring-gives-null-result

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