2014-01-08 65 views
-4

我從@「2014-01-08T00:00:00.000Z」從Web服務獲取日期組件。我需要將它轉換爲只提供年份,月份和日期的日期。請幫助將特定格式轉換爲NSDate

+0

http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns – Desdenova

+0

這個問題已經被問超過10000次,下一次嘗試使用谷歌 –

回答

2

使用此代碼來獲取當前日期

NSDateFormatter *dateFor=[[NSDateFormatter alloc]init]; 
NSString *currentDateString = @"2014-01-08T21:21:22.737+05:30"; 

[dateFor setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];   
NSDate *currentDate = [dateFor dateFromString:currentDateString]; 

NSLog(@"CurrentDate:%@", currentDate); 
+0

這不是問了什麼。他說'給我提供年份,月份和日期。' – Desdenova

+0

@Desdenova,但它提供年,月和日期的日期。 – ChenSmile

+0

當然,但你需要再次格式化,以消除時間。 – Desdenova

3

如果需要輸出年 - 月-date在這樣的格式,然後用下面的代碼。另外你需要的格式轉換成以下格式指定: -

NSString *currentDateString = @"2014-01-08T00:00:00.000Z"; 
self.dateFormatter=[[NSDateFormatter alloc]init]; 
[self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; 
NSDate *currentDate = [self.dateFormatter dateFromString:currentDateString]; 
[self.dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
    currentDateString=[self.dateFormatter stringFromDate:currentDate]; 
NSLog(@"CurrentDate:%@", currentDateString); 

輸出: -

CurrentDate:2014-01-08 
+0

@Hussan Shabbir我編輯答案。你的回答完美無需編輯抱歉我的錯誤。 –

+0

其正常np :) –

+0

謝謝你採取冷靜.. –

1

正從字符串的日期再次改變dateformatter的格式,然後經過使用獲得的字符串格式化。

NSString *currentDateString = @"2014-01-08T21:21:22.737+05:30"; 

NSDateFormatter *dateFor=[[NSDateFormatter alloc]init]; 
[dateFor setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];   
NSDate *currentDate = [dateFor dateFromString:currentDateString]; 
[dateFor setDateFormat:@"MMMM dd, yyyy"]; 

// above format will show date as Dec 31, 2013 something like this 
// can use other format as well like. [dateFor setDateFormat:@"yyyy-MM-dd"] 

NSString *dateString = [dateFor stringFromDate:currentDate]; 
相關問題