Parsing unsupported date formats in via Cocoa's NSDate
With the Cocoa framework how can I parse @"2008-12-29T00:27:42-08:00" into an NSDate object? The standard -dateWithString:
doesn't like it.
You can use NSDateFormatter to parse dates:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
date = [dateFormatter dateFromString:dateStr];
The unicode date format patterns defines the format string you can use with the setDateFormat:
method.
Note that if you're targeting 10.4 then you need to call: [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
. Not needed for iphone, or leopard as this mode is the default there.
如果您只需处理ISO 8601格式(该字符串是一个示例),则可以尝试使用ISO 8601解析器和解析器。
Actually, you need to set timezone, calendar and locale. If you don't set locale, an user has AM/PM time enabled the formatter will add AM/PM marker! If you don't set the timezone, it will use the current timezone, but will mark it as "Z" ("Zulu" or GMT). If you do not set calendar, users with Japanese Imperial calendar will have number of years since current Emperor's ascension instead of the number of years since Jesus Christ was born. Be sure to test in all of the scenarios I mentioned!
NSDateFormatter * f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
f.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
f.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
f.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
NSString * str = [f stringFromDate:someDate];
NSDate * date = [f dateFromString:dateStr];
链接地址: http://www.djcxy.com/p/5982.html