What is the easiest way to parse an RFC3339 date string in iOS?

The Youtube API returns a date string in RFC3339 format. In any case, I found how to disassemble it manually.

- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString // Returns a user-visible date time string that corresponds to the // specified RFC 3339 date time string. Note that this does not handle // all possible RFC 3339 date time strings, just one of the most common // styles. { NSString * userVisibleDateTimeString; NSDateFormatter * rfc3339DateFormatter; NSLocale * enUSPOSIXLocale; NSDate * date; NSDateFormatter * userVisibleDateFormatter; userVisibleDateTimeString = nil; // Convert the RFC 3339 date time string to an NSDate. rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease]; enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; [rfc3339DateFormatter setLocale:enUSPOSIXLocale]; [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString]; if (date != nil) { // Convert the NSDate to a user-visible date string. userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; assert(userVisibleDateFormatter != nil); [userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle]; [userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle]; userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date]; } return userVisibleDateTimeString; } 

I can make the function contain this, but I want to know if there is a predefined way for Cocoa funds or the standard C or POSIX library for this. And I want to use it if it is. Can you tell me if there is an easier way? Or would be very grateful if you confirm that this is the easiest way :)

+4
source share
3 answers

The pure material that comes with Cocoa is exactly what you do. You can make this method shorter and faster by creating a date formula elsewhere, possibly in init and using / reusing them in this method.

+2
source

You need two formats, because fractional seconds are optional, and the time zone should be Z5, not Z. Thus, you create two formats with formats

 @"yyyy'-'MM'-'dd'T'HH':'mm':'ssX5" @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSSSSX5" 

and try both of them. This is obvious to RFC3339; Your lines may not be in this format. Glad you did not ask RFC822 what it hurts to do right. But first you must have a method that returns NSDate, because most applications do not actually need a string formatted for the user.

+2
source

I'm having trouble parsing RFC 3339 in Obj-c, since fractional seconds and zone seem to be optional.

The most reliable feature I found was this Gist (from which I am not the author): https://gist.github.com/mwaterfall/953664

+1
source

Source: https://habr.com/ru/post/1391205/


All Articles