2012-03-07 18 views
0

我很難解析類型的日期字符串:3\/3\/2012 12:00:00 AM。我有以下代碼:解析NSDate字符串與MM/d/YYY hh:mm aaa格式不起作用

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
    formatter.dateFormat = @"MM/d/YYYY hh:mm aaa"; 
    conference.beginDate = [formatter dateFromString:[jsonElement valueForKey:@"BeginDateMember"]]; 

但不幸的是,我所有的beginDatenull

我不知道是否:a)我需要在格式中包含轉義反斜槓,b)我指定的語言環境錯誤,c)我指定的格式錯誤,或d)上述的某些組合。

這是一個有點非標準的日期格式,所以幫助表示讚賞。

回答

0

您格式看起來是斷了一下:

formatter.dateFormat = @"MM/d/yyyy hh:mm a"; 

你可以找到支持甲酸here的列表。

此外,如果你不使用ARCautoreleaseNSLocale

formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; 
1

你可以試試這個:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"MM/d/YYYY hh:mm aaa"]; //notice the change here .. 
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; //.. and here 
conference.beginDate = [formatter dateFromString:[jsonElement valueForKey:@"BeginDateMember"]]; 

[dateFormatter release]; 

如果仍然無效請確保您的jsonElement實際上有一個值。

+0

我的'jsonElement'是一個字符串... – 2012-03-07 13:07:31

+0

對不起,我沒有注意到那裏的區別。然而,看到它是有價值的。並使用setLocale/setDateFormat方法。 – 2012-03-07 13:09:35