开发者

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 dateFromStri开发者_如何转开发ng: [dict valueForKey:@"Message"]], m.LastSyncDate);

RETURNS:

New LastSyncDate: (null) : (null)


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);


You need to set the date format string.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜