Need to convert custom timestamp to different format in Objective-C iOS

情到浓时终转凉″ 提交于 2019-12-25 17:04:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!