2011-11-22 67 views
0

我試圖將日期從MMM dd,YYYY轉換爲YYYY-MM-dd。NSDate轉換

NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init]; 
    [importDateFormat setDateFormat:@"MMM dd, YYYY"]; 

    NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text]; 

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"YYYY-MM-dd"]; 

    NSString *dateImported = [dateFormat stringFromDate:importedDate]; 

日期從expiresOn.text(標籤)帶來的是: 2012年10月8日

包含在dateImported轉換後的日期是: 2011-12-25

上午我錯過了什麼?我的日期格式化程序有問題嗎?

回答

3

那麼有兩件事是錯誤的,第一個是yyyy而不是YYYYY並且由於您將月份解析爲單詞,因此您需要告訴日期格式化程序需要哪種語言。

NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init]; 
[importDateFormat setDateFormat:@"MMM dd, yyyy"]; 
importDateFormat.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en"] autorelease]; 

NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text]; 

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"yyyy-MM-dd"]; 

NSString *dateImported = [dateFormat stringFromDate:importedDate]; 

如果使用ARC,然後刪除NSLocale自動釋放部分;如果您不使用ARC,則需要釋放NSDateFormatter