Search code examples
iphoneobjective-ciosnsdateformattersubscription

Auto-renewable subscription receipt date format


I'm struggling to figure out the formatting for the following date:

2011-05-24 19:02:32 Etc/GMT

This date is returned from Apple's receipt validation service and I need to turn it into a NSDate for some comparison operations. The real trouble is related to the timezone.

Here's some code I've already written:

        NSDictionary *receiptData = [info valueForKey:@"expires_date"];

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

        [f setLocale:[NSLocale currentLocale]];
        [f setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        [f setDateFormat:@"yyyy-MM-dd HH:mm:ss vvvv"];

        NSLog(@"%@", [f stringFromDate:[NSDate date]]);

        NSDate *subPurchaseDate = [f dateFromString:[receiptData valueForKey:@"original_purchase_date"]];

        [f release];

I've tried all combinations of 'v's and 'Z's that I can think of. Any insight?


Solution

  • By looking at the date format documentation I got the correct format, is works well for me:

            NSDateFormatter * formatter = [NSDateFormatter new];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss VV";
    
            NSDate * purchaseDate = [formatter dateFromString:latestTransaction[@"original_purchase_date"]];
            NSDate * expirationDate = [formatter dateFromString:latestTransaction[@"expires_date"]];
    

    No need to set the time zone on the formatter since it's embedded in the string.
    Manipulating the date string to parse it is not a good idea.

    Source: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns