Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting date from string in objective C

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);
}
like image 254
Chengappa C D Avatar asked Dec 16 '22 03:12

Chengappa C D


1 Answers

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 ;-)

like image 199
falsecrypt Avatar answered Dec 30 '22 15:12

falsecrypt