Search code examples
objective-cnsdatensdateformatterrfc3339

Date format for 2008-02-01T10:03:23.793-06:00


In my project i am getting "2008-02-01T10:03:23.793-06:00" this date format in string i have to convert into NSDate i am using

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; 

NSDate* dateFromString = [dateFormatter dateFromString:@"2008-02-01T10:03:23.793-06:00"];

But when i am print date value using NSLog i am getting value as null.

Please help me out

Thank You


Solution

  • 2020 Update


    It turns out that updates to the NSDateFormatter make to code from the original answer work as expected, when back in 2010 it would fail to parse

    Objective-C:

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; 
    
    NSDate* dateFromString = [dateFormatter dateFromString:@"2008-02-01T10:03:23.793-06:00"];
    

    Swift:

    let dateFormatter = DateFormatter()
    
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    let dateFromString = dateFormatter.date(from: "2008-02-01T10:03:23.793-06:00")
    

    Original answer from 2010


    NSDateFormatter won't be able to parse it, because the timezone doesn't conform with RFC 822 or GMT standard. The problem is on the last ":" to have it you need the "GMT".

    The date that you have respects the RFC 3339.

    You will need to use a NSFormatter to parse it. You should use getObjectValue:forString:errorDescription:

    Set the string @"yyyy-MM-dd'T'HH:mm:ss.SSSZ".