Sheehan Alam
Sheehan Alam

Reputation: 60879

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?

Upvotes: 14

Views: 22503

Answers (3)

Shan
Shan

Reputation: 131

You can also try

NSString *dateString = [NSString stringWithFormat:[NSDate date]];

Upvotes: 3

Niko
Niko

Reputation: 2543

You can also do this way :

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"MM/dd/yyyy"];
NSString *result = [df stringFromDate:date];
[df release];

Upvotes: 10

Bjarne Mogstad
Bjarne Mogstad

Reputation: 1154

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

Upvotes: 15

Related Questions