Converting a date format in objective C

给你一囗甜甜゛ 提交于 2019-11-28 08:55:37
Suhail Patel

You've got your Date Format wrong for the style of Date you are passing in. Here is a document explaining the different modifiers: Date Format Patterns

To parse the Date "Sun Jul 17 07:48:34 +0000 2011", you'd need a Format like so:

[dateFormat setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];

To get it into the following format: "2011-07-17 07:48:34", here is the full code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
NSDate *date  = [dateFormatter dateFromString:sDate];

// Convert to new Date Format
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *newDate = [dateFormatter stringFromDate:date]; 

If sDate is your string that's in the format "Sun Jul 17 07:48:34 +0000 2011", you have to convert that into a NSDate. Then, you can use a second NSDateFormatter to convert this date into your desired format "yyyy-MM-dd HH:mm:ss".

If you need to figure out the string needed to convert, this site has a great reference: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

e.g. "Sun Jul 17 07:48:34 +0000 2011" can be parsed with

[dateFormatter setDateFormat:@"EEE MMM d HH:mm:ss ZZZ yyyy"];

As a bit of advice, non-standard dates like "Jul" (should be July) can make problems here. It's faster to just convert the needed parts in plain C, with strftime(). See the reference: http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst263.htm

You can then convert the unix timestamp back in a NSDate with

[NSDate dateWithTimeIntervalSince1970:]

Using C for date/time parsing is usually up to 10x faster. NSDateFormatter is a slow dog.

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