Ofir Malachi
Ofir Malachi

Reputation: 1286

NSString to NSDate = nil (with timezone)

Trying to convert "expires_date" string value into NSDate object.

Any suggestions?

-(NSDate*)expires_date{
    NSMutableDictionary * dictionary = [_dictionary mutableCopy];
    NSString * date_string = [dictionary valueForKey:@"expires_date"];

    //date_string = "2019-08-18 15:12:09 America/Los_Angeles"

    NSDateFormatter *dateFormatter = [IAPSKReceipt formatter];
    NSDate *date = [dateFormatter dateFromString:date_string];
    return date;
}

+(NSDateFormatter*)formatter{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    dateFormatter = @"yyyy-MM-dd HH:mm:ss";
    dateFormatter = [NSTimeZone timeZoneForSecondsFromGMT:0];
    return dateFormatter;
}

Upvotes: 0

Views: 85

Answers (2)

Vaiden
Vaiden

Reputation: 16142

In addition to @Shai Mishali's answer:

Considering the timezone, your date does not seem to be RFC3339 nor ISO8601 compliant.

ISO8601 allows substituting the 'T' in the middle for a ' ' so you will not get a nil response. However since the timezone is not according to spec, it will not be parsed and the expected response will not be in the desired LA timezone (PST, GMT-8).

Here is your date in legal ISO8601/RFC3339:

"2019-08-18T15:12:09-0800"

Upvotes: 1

Shai Mishali
Shai Mishali

Reputation: 9402

you might want to look into ISO8601DateFormatter which is tailored for what you’re trying to do:

https://developer.apple.com/documentation/foundation/iso8601dateformatter

Upvotes: 2

Related Questions