Parsing unsupported date formats in via Cocoa'

2019-01-17 16:56发布

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.

4条回答
叼着烟拽天下
2楼-- · 2019-01-17 17:23

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];
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-17 17:27

If you only need to handle the ISO 8601 format (of which that string is an example), you might try my ISO 8601 parser and unparser.

查看更多
何必那么认真
4楼-- · 2019-01-17 17:29

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.

查看更多
Rolldiameter
5楼-- · 2019-01-17 17:39

How the time zone is set changed from ios 5 to ios 6. iOS 6 supports the format +01:00 using ZZZZZ but ios 5 doesn't. I solved this issue with this solution which worked for me to parse a date with the following format in ios 5 and 6.

2013-05-07T00:00:00+01:00

NSMutableString *newDate = [date mutableCopy];
NSRange range;
range.location = 22;
range.length = 1;
[newDate replaceCharactersInRange:range withString:@""];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZ"];    
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:newDate];
查看更多
登录 后发表回答