2014-07-17 63 views
1

你好,我有麻煩轉換字符串日期和日期字符串只有時間。 結果爲空。字符串日期和時間

下面是我在做什麼:

我有一本字典,隨着時間的推移它:

@"Time" : @"2014-07-17T10:38:00+03:00" 

我這樣做:

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init]; 
[timeFormat2 setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; 
NSDate *date = [timeFormat2 dateFromString:[JSON valueForKey:@"Time"]]; 

然後將此:

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init]; 
[timeFormat setDateFormat:@"HH:mm:ss"]; 
NSLog(@"%@",[timeFormat stringFromDate:date]); 
cell.iboTimeLabel.text = [timeFormat stringFromDate:date]; 

並且該值爲空。

我的錯誤在哪裏?

+1

刪除TimeString中的所有單引號並嘗試。 –

+1

你可以試試這個:[timeFormat2 setDateFormat:@「yyyy-MM-ddTHH:mm:ssZ」];?目前在這裏運行Windows ... – Akaino

+0

Akaino,沒有不加引號不起作用 – Cheese

回答

2

刪除時間字符串中的單引號並嘗試。使用以下日期格式化程序。

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init]; 
[timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; 
NSDate *date = [timeFormat2 dateFromString:@"2014-07-17T10:38:00+03:00"]; 
+2

想到了相同的^^你稍微快一點:P – Akaino

3

你設置你的字符串日期的格式錯誤檢查與婁代碼:

NSString *[email protected]"2014-07-17T10:38:00+03:00"; 

    NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init]; 
    [timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; 
    NSDate *date = [timeFormat2 dateFromString:str]; 


    [timeFormat2 setDateFormat:@"HH:mm:ss"]; 

    NSString *final = [timeFormat2 stringFromDate:date]; 
    NSLog(@"%@",final); 
+0

謝謝。但蘇雷什是第一個有正確答案的人。我會投票給你的。 – Cheese

1

嘗試用這種格式

NSDateFormatter *timeFormat2 = [[NSDateFormatter alloc] init]; 
[timeFormat2 setDateFormat:@"yyyy-MM-dd'T'hh:mm:ssZZZZZ"]; 
NSDate *date = [timeFormat2 dateFromString:@"2014-07-17T10:38:00+03:00"]; 


NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init]; 
[timeFormat setDateFormat:@"HH:mm:ss"]; 
NSLog(@"%@",[timeFormat stringFromDate:date]); 

它的工作。我希望這是爲你工作。

+0

謝謝。但蘇雷什是第一個有正確答案的人。我會投票給你的。 – Cheese

+2

儘管它已經足夠清晰,您還沒有回答這個問題。一個好回合值得另一個... – trojanfoe

1

將日期格式設置爲[timeFormat2 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];應該做的伎倆,我建議reading this document下次你處理這樣的問題。