I have to obtain date from a string, here the string will be in format "Monday 02,Dec 2013" i have to convert it to "2013-12-2" .I used the following code but I'm getting wrong output :
-(void)dateSelectedInPickerView:(NSString *)dateSelected{
NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
[dateFormatterForGettingDate setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
// Parse the string representation of the date i.e Monday 2,Dec 2013
NSDate *dateFromStr = [dateFormatter dateFromString:dateSelected];
NSLog(@"date selected : %@",dateFromStr);
NSDateFormatter *tempFormatter=[[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:@"YYYY-MM-dd"];
self.reservationDateSelected=[tempFormatter stringFromDate:dateFromStr];
NSLog(@"date Selected : %@",self.reservationDateSelected);
}
try this, it works for me with Monday 02,Dec 2013
:
-(void)dateSelectedInPickerView:(NSString *)dateSelected{
NSDateFormatter *dateFormatterForGettingDate = [[NSDateFormatter alloc] init];
[dateFormatterForGettingDate setDateFormat:@"EEEE dd,MMM yyyy"];
[dateFormatterForGettingDate setLocale:[NSLocale localeWithLocaleIdentifier:@"EN"]];
// Parse the string representation of the date i.e Monday 2,Dec 2013
NSDate *dateFromStr = [dateFormatterForGettingDate dateFromString:dateSelected];
NSLog(@"date selected : %@", [dateFromStr descriptionWithLocale:[NSLocale currentLocale]]);
NSDateFormatter *tempFormatter=[[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:@"yyyy-MM-dd"];
self.reservationDateSelected=[tempFormatter stringFromDate:dateFromStr];
NSLog(@"date Selected : %@",self.reservationDateSelected);
}
Read this, if want to know more about Date Format Patterns ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With