问题
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
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/10823129/need-to-convert-custom-timestamp-to-different-format-in-objective-c-ios