2010-12-06 32 views
0
I need to convert this string in to the date: 

    02-09-2011 20:54:18 

I am trying the `dateFromString` method but every time it is returning (null), what NSDateFormatter should I use?, I have tried 
`[formatter setDateFormat:@"yyyy-MM-dd"]` and `[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]`. 


Here is my code: 
NSString *finalDate = @"02-09-2011 20:54:18"; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd"]; 

NSDate *dateString = [formatter dateFromString:finalDate]; 
NSLog(@"%@",dateString); 


Thanks. 
+1

有一段時間我認爲這是某種形式的東西計算機科學問題的呼籲一個「大冶形式」 ......你讓我失望:( – 2010-12-06 07:26:06

+0

沒有人能讓大冶形式的字符串。 – Ishu 2010-12-06 07:27:51

回答

15

可以將包含使用NSDateFormatter用下面的代碼的日期到的NSDate一個NSString的:

// Your date as a string 
NSString *finalDate = @"02-09-2011 20:54:18"; 

// Prepare an NSDateFormatter to convert to and from the string representation 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

// ...using a date format corresponding to your date 
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"]; 

// Parse the string representation of the date 
NSDate *date = [dateFormatter dateFromString:finalDate]; 

// Write the date back out using the same format 
NSLog(@"Month %@",[dateFormatter stringFromDate:date]); 
相關問題