Possible Duplicate:
how to convert datetime format in NSString?
I have stored date in string from json parsing. The format of date is 2011-1-24. Now i want to convert into MM-dd-YYYY format. For that i am using this code
NSString *stringDate =[NSString stringWithFormat:@"%@",[list_date objectAtIndex:indexPath.row]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
NSDate *date = [dateFormatter dateFromString:stringDate];
NSString *newDate = [dateFormatter stringFromDate:date];
But it show null value. What is problem in this code?
Thanks in advance...
Parth Bhatt
It is different from @Mayur Joshi's answer though it looks to be same.
This is sure to work for you.
NSString *dateString = @"2011-09-19";
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [format dateFromString:dateString];
[format setDateFormat:@"MM-dd-yyyy"];
NSString* finalDateString = [format stringFromDate:date];
[format release];
I hope this helps you.
If you need any help on this then please leave a comment below.
Also you can refer to this link for more help. This link is really similar to what you want, only the target date Format is different.
NSString *dateStr = @"2011-1-24";
//OR if you have date then declare dateStr like this,
NSString *dateStr = [NSString stringWithFormat:@"%@",yourDate];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-M-dd"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat setDateFormat:@"MM-dd-YYYY"];
NSString* temp = [dateFormat stringFromDate:date];
[dateFormat release];
NSLog(@"%@",temp);
来源:https://stackoverflow.com/questions/7466801/how-change-the-date-format-which-is-stored-in-string-objective-c