Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date in MM/dd/yyyy format in xcode?

I have a UIDatePicker and I m getting the selected date from it in yyyy-MM-dd format.Now I want to convert it to MM/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.

like image 485
Honey Avatar asked Oct 30 '12 12:10

Honey


People also ask

How do I change the date format in Swift?

let date = Date(); let dateFormatter = DateFormatter(); Date will give us the current date and time with respect to our current time zone. For me, it's Wednesday, June 1st, 2022. dateFormatter is an instance of the DateFormatter class that allows us to operate various formatting functions on our date .

What is dateFormatter in Swift?

A formatter that converts between dates and their textual representations.

What is en_US_POSIX?

en_US_POSIX was invented to refer to the C (or 'null') locale code used in POSIX libraries.


2 Answers

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);
like image 153
Paras Joshi Avatar answered Oct 24 '22 04:10

Paras Joshi


df.dateFormat = @"MM/dd/yyyy";

like image 39
Eric Avatar answered Oct 24 '22 03:10

Eric