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.
Asked
Active
Viewed 8,514 times
0

Developer
- 6,375
- 12
- 58
- 92
-
1For a while I thought this was some kind of computer science question about something called a "Daye form"... you disappointed me :( – Matti Virkkunen Dec 06 '10 at 07:26
-
No one can make Daye form string. – Ishu Dec 06 '10 at 07:27
-
Why you set date format two times. give code for solution you definitely make some silly mistake – Ishu Dec 06 '10 at 07:29
-
why not you give some code where you get problem.And also make difference for different cases as well. – Ishu Dec 06 '10 at 07:34
2 Answers
15
You can convert a NSString containing a date to a NSDate using the NSDateFormatter with the following code:
// 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]);

Niels Castle
- 8,039
- 35
- 56
-
THANKS A TON, Ur answer is exactly i was looking for, i was expecting thee error in the date Format, i searched a lot for the correct date format but didn't get thanks once again :-) – Developer Dec 06 '10 at 08:04
-
Converting a string to Date object returns the date in GMT(Greenwich Mean Time). – Abhilash Reddy kallepu Jan 04 '13 at 06:11
0
Surely it's easier to search than it is to ask?