Slee
Slee

Reputation: 28248

NSDate from NSString returning null problem

Here is my string stored in the value below: 2011-03-13 23:22:05

Here is my code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter dateFromString: [dict valueForKey:@"Message"]];
[m setLastSyncDate:[formatter dateFromString: [dict valueForKey:@"Message"]]];
NSLog(@"New LastSyncDate: %@ : %@",[dict valueForKey:@"Message"], m.LastSyncDate);

This is the response I get in console:

New LastSyncDate: 2011-03-13 23:22:05 : (null)

Why am I getting a (null) here?

UPDATE CODE:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
            Manufacturer *m = [self.manufacturers objectAtIndex:i];
            [m setLastSyncDate:[formatter dateFromString: [dict valueForKey:@"Message"]]];
            NSLog(@"New LastSyncDate: %@ : %@",[formatter dateFromString: [dict valueForKey:@"Message"]], m.LastSyncDate);

RETURNS:

New LastSyncDate: (null) : (null)

Upvotes: 0

Views: 525

Answers (2)

Dave DeLong
Dave DeLong

Reputation: 243156

You need to set the date format string.


You also need to make sure that [dict valueForKey:@"Message"] isn't returning nil.

Upvotes: 3

saturngod
saturngod

Reputation: 24949

updated code:

 NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];


    //2011-03-13 23:22:05
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; ///add this line


    NSString* message;
    NSDate* LastSyncDate;

    message=@"2011-03-13 23:22:05";
    LastSyncDate=[formatter dateFromString:message];

    NSLog(@"New LastSyncDate: %@ : %@",message, LastSyncDate);

Upvotes: 3

Related Questions