iPhone:无法从字符串转换日期 [英] iPhone : Unable to convert date from string

查看:86
本文介绍了iPhone:无法从字符串转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将字符串转换为NSDate。

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

我设置 OLD_DATE 如下:

NSDate *oldDate = [NSDate date];
NSString *old = [[NSString stringWithFormat:@"%@",oldDate] retain];
[[NSUserDefaults standardUserDefaults] setObject:old forKey:@"OLD_DATE"];

但是我在 NSLog中得到空(@旧日期:% @,oldDate); :(

我发现很多类似的链接使用相同的代码,并且可以正常使用。

I found many similar links with the same code and works fine for them.

那么我的代码可能有什么问题呢?

So what could be problem with my code ?

推荐答案

不要将日期转换为字符串:

Don't covert the date to string:

NSDate *oldDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:oldDate forKey:@"OLD_DATE"];

只读出日期:

NSDate *old = [[NSUserDefaults standardUserDefaults] objectForKey:@"OLD_DATE"];

在保存到 NSUserDefaults 之前,确实没有任何理由将日期与字符串相结合。

There really should not be any reason to concert the date to a string before saving to in the NSUserDefaults.

但是如果你想将字符串回归到日期,你会需要正确的格式。
NSDate描述类似于 2011-11-11 12:58:36 +0000

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

这篇关于iPhone:无法从字符串转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆