2014-10-20 47 views
1

想知道是否有一個簡單的轉換採取格式爲dd /月/年的日期,並將其轉換爲MM/DD/YYYY顯示量。NSDateFormat DD/MM/YYYY到MM/DD/YYYY的iOS

試圖當前的代碼:

//in dd/MM/yyyy format string below. 
    NSString *stringToFormat = @"28/05/1991"; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

    [dateFormatter setDateFormat:@"MM/dd/yyyy"]; 

    NSDate *date = [dateFormatter dateFromString:stringToFormat]; 

然而,日期會在這種情況下返回零。任何幫助,將不勝感激。謝謝。

+2

請搜索。有無數如何將日期字符串從一種格式轉換爲另一種格式的例子。 – rmaddy 2014-10-20 18:20:21

+0

@rmaddy:d::P – 2014-10-20 18:24:54

+0

@FahimParkar這不會是一個答案,只是一個評論,如果你把上面的註釋與谷歌的搜索鏈接的答案,我會給予好評。 – rmaddy 2014-10-20 18:26:36

回答

3

你必須「解碼」,然後選擇「編碼」。您目前正試圖將28解析爲一個月。試試這個:

//in dd/MM/yyyy format string below. 
NSString *stringToFormat = @"28/05/1991"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setDateFormat:@"dd/MM/yyyy"]; 

NSDate *date = [dateFormatter dateFromString:stringToFormat]; 

[dateFormatter setDateFormat:@"MM/dd/yyyy"]; 

[dateFormatter stringFromDate:date];