Swapnil
Swapnil

Reputation: 1878

String to NSDate

I am trying to convert string to date. have used the following code. But getting wrong date.

Thanks,

NSString *dateString = [NSString stringWithFormat:@"12-07-2011"];
//NSString *dateString = [NSString stringWithFormat:@"%d-%d-%d", selectedDate.day, selectedDate.month, selectedDate.year];
NSLog(@"%@",dateString);

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

[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:@"dd-mm-yyyy"];

NSDate* d = [dateFormatter dateFromString:dateString];
NSLog(@"%@",d);               
                      
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selected Date" message: [NSString stringWithFormat:@"%@",d] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Upvotes: 2

Views: 784

Answers (2)

Joe
Joe

Reputation: 57169

The problem is you are using the minute and not the month. M

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

Unicode Date Format Patterns

Upvotes: 6

jamapag
jamapag

Reputation: 9318

Use:

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

Upvotes: 4

Related Questions