-1

I have a string "2012-06-04" and am having a hard time converting it to: June 4, 2012.

Is there a quick way to transform this? I come from a ruby world where you would convert everything to seconds and that back out to the format you need it. Is there a reference that shows how to do that?

Thanks

4

2 回答 2

3

One way to do so is to convert the string to an NSDate using the NSDateFormatter with the 2012-06-04 format, and then convert the NSDate back to a string using the June 4, 2012 format:

NSString* input = @"2012-06-04";

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate* date = [df dateFromString:input];
[df setDateFormat:@"MMMM d, yyyy"];

return [df stringFromDate:date];

The format string's syntax is described in UTS #35.

于 2012-05-30T19:53:20.163 回答
1

Something like

NSDateFormatter *fromDateFormatter = [[NSDateFormatter alloc] init];
fromDateFormatter.dateFormat = @"yyyy-MM-dd";

NSDate *date = [fromDateFormatter dateFromString:@"2012-06-04"];

NSLog(@"%@", date);

NSDateFormatter *toDateFormatter = [[NSDateFormatter alloc] init];
toDateFormatter.dateFormat = @"MMMM d, yyyy";

NSString *toDate = [toDateFormatter stringFromDate:date];

NSLog(@"%@", toDate);

#=> 2012-05-30 20:51:12.205 Untitled[1029:707] 2012-06-03 23:00:00 +0000
#=> 2012-05-30 20:51:12.206 Untitled[1029:707] June 4, 2012

To work this out you can use Apple's class references NSDateFormatter and other sources like this IPHONE NSDATEFORMATTER DATE FORMATTING TABLE and some trial and error

于 2012-05-30T19:51:51.063 回答