2013-03-29 76 views
0

我得到JSON解析日期,我想使用NSDateFormatter,但沒有成功。關於JSON日期轉換錯誤

1.JSON獲取控制檯登錄

IncidentReceiveTime = "/Date(1353914100000+0800)/"; 

2.my代碼

NSString *dateStr =[NSString stringWithFormat:@"%@",[[[DateSortArry objectAtIndex:0] objectForKey:@"IncidentReceiveTime"]stringByReplacingOccurrencesOfString:@"/" withString:@""]]; 
    NSLog(@"dateStr:%@",dateStr); 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setLocale:[NSLocale currentLocale]]; 
    [dateFormatter setDateFormat:@"yyyy-MM-ddHH"]; 
    NSDate *date = [dateFormatter dateFromString:dateStr]; 
    NSLog(@"date:%@",date); 

3.NSDateFormatter控制檯日誌

dateStr:Date(1361943694000+0800) 
date:(null) 
+0

嘗試'NSDateFormatter'對象的'setDateStyle:'屬性。 – Malloc

+0

[解析iPhone上的JSON日期](http://stackoverflow.com/questions/1757303/parsing-json-dates-on-iphone) – rmaddy

回答

2

請參閱我的答案:

iPhone:How to convert Regular Expression into Date Format?

這裏彷彿情況下,將來上面的鏈接出現故障那麼這個答案不會成爲useles我張貼從我回答這個代碼在上面的鏈接:

- (NSDate*) getDateFromJSON:(NSString *)dateString 
{ 
    // Expect date in this format "/Date(1268123281843)/" 
    int startPos = [dateString rangeOfString:@"("].location+1; 
    int endPos = [dateString rangeOfString:@")"].location; 
    NSRange range = NSMakeRange(startPos,endPos-startPos); 
    unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue]; 
    NSLog(@"%llu",milliseconds); 
    NSTimeInterval interval = milliseconds/1000; 
    return [NSDate dateWithTimeIntervalSince1970:interval]; 
} 

一旦你得到的NSDate對象從上面的方法:

NSDateFormatter *dateForm = [[NSDateFormatter alloc] init]; 
[dateForm setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
NSString *dateStr = [dateForm stringFromDate:<YourNSDateObject>]; 
[dateForm setDateFormat:@"<Your Desired Date Format>"]; 
NSDate *desireddate = [dateForm dateFromString:dateStr]; 

希望這會有所幫助。

+0

夢幻般的答案。非常感謝。 – Katushai