NSDate from NSString gives null result

2020-03-31 06:59发布

问题:

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.