Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse ISO8601 date in Objective-C (iPhone OS SDK)

How do I parse "2010-04-30T00:45:48.711127" into an NSDate? (and maintain all precision)

like image 813
bradley.ayers Avatar asked May 09 '10 02:05

bradley.ayers


1 Answers

You have your work cut out for you.

NSDate will throw out any values past 3 decimal places for seconds. You can create a subclass of NSDate to hold on to that precision but you'll also need to implement your own parsing and custom formatters to input and display it since NSDateFormatter and CFDateFormatter, which it is built on, will also truncate precision after 3 decimal places. Depending on what you're doing though that shouldn't be all that hard.

This is a simple subclass (not implementing NSCoding or NSCopying) that will hold on to all the precision you give it.

@interface RMPreciseDate : NSDate {
    double secondsFromAbsoluteTime;
}

@end

@implementation RMPreciseDate

- (NSTimeInterval)timeIntervalSinceReferenceDate {
    return secondsFromAbsoluteTime;
}

- (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secsToBeAdded {
    if (!(self = [super init]))
        return nil;

    secondsFromAbsoluteTime = secsToBeAdded;

    return self;
}

@end

You can then ask for the -timeIntervalSince1970 to get UNIX epoch time.

There is an ISO8601 date/time parser class already out there, but since it's using NSDateComponents to generate its date it's limited to full-second precision currently, but you could use it as a starting point perhaps to create more precise representations.

like image 193
Ashley Clark Avatar answered Nov 03 '22 00:11

Ashley Clark