2012-01-30 115 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

相關問題