iPhone : Unable to convert date from string

£可爱£侵袭症+ 提交于 2019-12-11 08:26:20

问题


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

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