问题
I am trying to convert string into NSDate using following code.
NSString *old = [[NSUserDefaults standardUserDefaults] valueForKey:@"OLD_DATE"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *oldDate = [formatter dateFromString:old];
NSLog(@"Old Date : %@",oldDate);
I am setting OLD_DATE
as following :
NSDate *oldDate = [NSDate date];
NSString *old = [[NSString stringWithFormat:@"%@",oldDate] retain];
[[NSUserDefaults standardUserDefaults] setObject:old forKey:@"OLD_DATE"];
But I am getting null in the NSLog(@"Old Date : %@",oldDate);
:(
I found many similar links with the same code and works fine for them.
So what could be problem with my code ?
回答1:
Don't covert the date to string:
NSDate *oldDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:oldDate forKey:@"OLD_DATE"];
To read out the date just:
NSDate *old = [[NSUserDefaults standardUserDefaults] objectForKey:@"OLD_DATE"];
There really should not be any reason to concert the date to a string before saving to in the NSUserDefaults
.
But if you want to concert the string back to a date you will need the correct format.
A NSDate descrption would be something like 2011-11-11 12:58:36 +0000
NSString *old = [[NSUserDefaults standardUserDefaults] valueForKey:@"OLD_DATE"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSDate *oldDate = [formatter dateFromString:old];
NSLog(@"Old Date : %@",oldDate);
来源:https://stackoverflow.com/questions/8094238/iphone-unable-to-convert-date-from-string