Convert date in MM/dd/yyyy format in xcode?
46,083
Solution 1
See Instruction or introduction with every line
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);
Solution 2
df.dateFormat = @"MM/dd/yyyy";
Solution 3
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MM/dd/yyyy"];
Solution 4
Just to see how it ends up:
NSDateFormatter* df = [[[NSDateFormatter alloc]init] autorelease];
df.dateFormat = @"MM/dd/yyyy";
NSString* dateString = [df stringFromDate:datePicker.date]; // Don't use leading caps on variables
NSLog(@"%@", dateString);
Solution 5
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];
Author by
Honey
Updated on June 20, 2020Comments
-
Honey about 4 years
I have a
UIDatePicker
and I m getting the selected date from it inyyyy-MM-dd
format.Now I want to convert it toMM/dd/yyyy
format ..How can i do it ?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);
Im getting 2012-10-30 but I want 10/30/2012.