在xcode中以MM/dd/yyyy格式转换日期?

Hon*_*ney 16 objective-c nsdate uidatepicker ios

我有一个UIDatePicker,我从格式中获取所选日期.现在yyyy-MM-dd我想将其转换为MM/dd/yyyy格式..我怎么能这样做?

NSDateFormatter *df=[[[NSDateFormatter alloc]init] autorelease];
df.dateFormat = @"yyyy-MM-dd";
NSArray *temp=[[NSString stringWithFormat:@"%@",[df stringFromDate:DatePicker.date]] componentsSeparatedByString:@""];

[dateString2 release];
dateString2=nil;
dateString2= [[NSString alloc]initWithString:[temp objectAtIndex:0]];
NSLog(@"%@",dateString2);
Run Code Online (Sandbox Code Playgroud)

我得到2012-10-30,但我想要10/30/2012.

Par*_*shi 46

请参阅每行的说明或介绍

NSString *str = @"2012-10-30"; /// here this is your date with format yyyy-MM-dd

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; //// here set format of date which is in your output date (means above str with format)

NSDate *date = [dateFormatter dateFromString: str]; // here you can fetch date from string with define format

dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];// here set format which you want...

NSString *convertedString = [dateFormatter stringFromDate:date]; //here convert date in NSString
NSLog(@"Converted String : %@",convertedString);
Run Code Online (Sandbox Code Playgroud)