2014-04-07 69 views
0

我從我的服務器,我把一個NSDictionary recing 3字符串值。然後我將這些值傳遞給一個NSDateComponent之後我嘗試創建一個NSDateFormatter,我很確定這是錯誤的。NSDate到NSString錯誤

的日期甲應該是01月2014,我recive是這樣

{ 
Day @"1" 
Month @"4" 
Year @"2014" 
} 

在下面的代碼,你會看到我都試過,但是我是這樣做的數據在兩個區域遇到問題,格式化爲NSDateFormatter,其次我如何將日期傳遞到NSString中,以便我可以將其顯示在我的標籤中。

NSDateComponents *recivedDate = [[NSDateComponents alloc] init]; 
[recivedDate setDay:[[recivedData objectForKey:@"Day"] intValue]]; 
[recivedDate setMonth:[[recivedData objectForKey:@"Month"] intValue]]; 
[recivedDate setYear:[[recivedData objectForKey:@"Year"] intValue]]; 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"dd-mm-yyy"]; 

NSString *dateString = [formatter stringFromDate:recivedDate]; 
dateResultLabel.text = dateString; 

任何幫助,將不勝感激。

+0

你會在recivedDate中得到什麼? –

+0

不應該是[formatter setDateFormat:@「dd-MM-yyyy」]; ? – Rashad

回答

3

你已經分叉日期組件好吧,但你沒有從它創建一個NSDate對象。 使用

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 
NSDate *date = [calendar dateFromComponents:recivedDate]; 

,然後使用我們的代碼,將其更改爲字符串

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"dd-MMM-yyy"]; 

NSString *dateString = [formatter stringFromDate:date]; 
dateResultLabel.text = dateString; 

PS:MMM應該給你,而不是04

+0

非常感謝! – HurkNburkS

0

這可能會幫助你...

NSDictionary *testDict = [[NSDictionary alloc] init]; 
[testDict setValue:@"14" forKey:@"Day"]; 
[testDict setValue:@"4" forKey:@"Month"]; 
[testDict setValue:@"2014" forKey:@"Year"]; 


NSString *str = [[[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Day"]] stringByAppendingString:[NSString stringWithFormat:@"%@-",[testDict objectForKey:@"Month"]]] stringByAppendingString:[NSString stringWithFormat:@"%@",[testDict objectForKey:@"Year"]]]; 





NSDateFormatter * formatter = [NSDateFormatter new]; 
[formatter setDateFormat:@"dd-MM-yyyy"]; 


NSDateFormatter *formatter1 = [NSDateFormatter new]; 
[formatter1 setDateFormat:@"dd-MMM-yyyy"]; 


NSLog(@"%@",[formatter1 stringFromDate:[formatter dateFromString:str]]); 
0
NSString *str_date = [NSString stringWithFormat:@"%@-%@-%@",[recivedData objectForKey:@"Day"],[recivedData objectForKey:@"Month"],[recivedData objectForKey:@"Year"]]; 

NSDateFormatter* df = [[NSDateFormatter alloc] init]; 
[df setDateFormat:@"dd-MM-yyyy"]; 
NSDate* d = [df dateFromString:str_date]; 
NSLog(@"%@", d); 
[df release]; 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"dd-MMMM-yyyy"]; 
NSString *stringFromDate = [formatter stringFromDate:d]; 
NSLog(@"%@",stringFromDate); 
[formatter release]; 

dateResultLabel.text = stringFromDate;