2012-01-30 116 views
1

我想将一个字符串日期转换为一个NSDate在格式中进行一些更改..但它总是返回零!Nsdate从字符串格式不工作

这是我的代码:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 

//Mon Jan 30 17:40:12 +0000 2012 
[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"]; 
[df setTimeStyle:NSDateFormatterFullStyle]; 
[df setFormatterBehavior:NSDateFormatterBehavior10_4]; 
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; 

NSDate *date1 = [df dateFromString:strData]; 

我已经试过这种格式过于:

[df setDateFormat:@"EEE MMM dd HH:mm:ss z yyyy"]; 

我已经试过此表:

http://www.deanoj.co.uk/ios-development/nsdateformatter-formatting-strings-reference/

我曾尝试这些链接..和很多其他人:

Convert NSString to NSDate with string format "Sun, 08 Jan 2012 13:57:38 +0000"

NSDateFormatter dateFromString returns nil

How to format Facebook/Twitter dates (from the JSON feed) in Objective-C

有人能帮助我吗?

在此先感谢!

+0

不要忘了释放分配的NSLocale,否则它会泄漏 – JustSid 2012-01-30 16:44:24

+1

@JustSid不会与ARC – ikuramedia 2012-01-30 16:47:11

回答

2

如果我把你的代码并修改它以这样的:

[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"]; 
// [df setTimeStyle:NSDateFormatterFullStyle]; 
// [df setFormatterBehavior:NSDateFormatterBehavior10_4]; 
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; 

NSDate *date1 = [df dateFromString:@"Mon Jan 30 17:40:12 +0000 2012"]; 
NSLog(@"date is %@", date1); 

我越来越:

2012-01-30 11:36:38.339 TestApp[32182:f803] date is 2012-01-30 17:40:12 +0000 

好像你应该需要做的是注释(或删除)这两个线。

+0

是的..这是真的..我不知道我为什么这么做..非常感谢你的朋友! – 2012-01-30 16:41:47

相关问题