Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSDate to NSString

I have the following:

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
[df release];

I would like the output string to be "9/20/10"

How can I do this?

like image 448
Sheehan Alam Avatar asked Jul 28 '10 18:07

Sheehan Alam


People also ask

How to convert NSDate to NSString in objective-C?

Objective-C Language NSDate Converting NSDate to NSString How we can do that?, It is very simple. Just 3 steps. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; Set the date format in which you want your string.


2 Answers

You can do it like this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
NSString *result = [formatter stringFromDate:[NSDate date]];

This will display it in the users settings (but in a similar way), so for me results will be 7/28/10

like image 163
Bjarne Mogstad Avatar answered Oct 21 '22 06:10

Bjarne Mogstad


You can also do this way :

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"MM/dd/yyyy"];
NSString *result = [df stringFromDate:date];
[df release];
like image 37
Niko Avatar answered Oct 21 '22 06:10

Niko