1
votes

In my application I am getting an NSString with the date as 01-22-12(MM-dd-yy). Now I want to convert that string into an NSDate. I used the code below. But it is giving the date as 2012-01-04 05:00:00 +0000

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yy"];
NSDate *dateFromString = [dateFormatter dateFromString:self.selectedWeek];

What is the proper way to convert my string to an NSDate?

2
Your question is not clear. What do you want exactly? - Ares
need nsdate value with same format. - Kevin Jack

2 Answers

1
votes

From your original question I'm not totally clear whether you want:

1 the string as an NSDate.

or

2 to be able to get the original date NSString back out of an NSDate instance.

Your code is basically right. I just ran a slightly adapted version of it, which seemed to work fine:

NSString *dateString = @"01-22-12";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"MM-dd-yy"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *outString = [dateFormatter stringFromDate:date];

NSLog(@"%@",date);
NSLog(@"%@",outString);

This produced:

2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 2012-01-22 00:00:00 +0000
2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 01-22-12

So, either way the result seems to be what you were looking for. I suspect that the reason you are getting an incorrect value is that self.selectedWeek doesn't have the value you think it does. I'd inspect it, either in the debugger or with NSLog. If you are creating it somewhere else using another format string, be aware that they can be tricky and slightly unintuitive - for instance s means seconds, but S means fractions of a second. Documentation available here - most recent Unicode formatting standard here (ios6.0/OSX 10.8) - also linked to in previous link, as are all previous relevant standards

0
votes

you can use descriptionWithCalendarFormat:timeZone:locale:

NSString * mydate =  [dateFromString descriptionWithCalendarFormat:@"%Y-%m-%d"
                                timezone:nil
                                  locale:nil];