I need to convert NSString like this : "2012-08-01T12:43:35+02:00" to NSDate, but i don't find the good format...
I use this category code to convert NSString to NSDate :
[NSDate dateFromString:@"2012-08-01T12:43:35+02:00" withFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
+ (NSDate*) dateFromString:(NSString*)dateString withFormat:(NSString*)format
{
return [self dateFromString:dateString withFormat:format andLocaleIdentifier:@"fr"];
}
+ (NSDate*) dateFromString:(NSString*)dateString withFormat:(NSString*)format andLocaleIdentifier:(NSString*)localeIdentifier
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
[dateFormatter setLocale:locale];
[locale release];
NSDate *returnDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];
return returnDate;
}
I tried all the format i can, but no one is correct...
yyyy-MM-dd'T'HH:mm:ss >> 2012-08-04T18:05:14
yyyy-MM-dd'T'HH:mm:ssv >> 2012-08-04T18:05:14France Time
yyyy-MM-dd'T'HH:mm:ssvv >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssvvv >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssV >> 2012-08-04T18:05:14CEST
yyyy-MM-dd'T'HH:mm:ssVV >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssVVV >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:ssVVVV >> 2012-08-04T18:05:14France Time
yyyy-MM-dd'T'HH:mm:ssz >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:sszz >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:sszzz >> 2012-08-04T18:05:14GMT+02:00
yyyy-MM-dd'T'HH:mm:sszzzz >> 2012-08-04T18:05:14Central European Summer Time
yyyy-MM-dd'T'HH:mm:ssZ >> 2012-08-04T18:05:14+0200
yyyy-MM-dd'T'HH:mm:ssZZ >> 2012-08-04T18:05:14+0200
yyyy-MM-dd'T'HH:mm:ssZZZ >> 2012-08-04T18:05:14+0200
yyyy-MM-dd'T'HH:mm:ssZZZZ >> 2012-08-04T18:05:14GMT+02:00
How can i do ?
[Edit] First ugly solution :
- Delete the last colon with a regex
- Convert the string with this format "yyyy-MM-dd'T'HH:mm:ssZZZ"
There is the regex
NSString* dateString = @"2012-08-01T12:43:35+02:00";
NSMutableString* dateWithoutColonString = [dateString mutableCopy];
NSRegularExpression* lastColonRegex = [NSRegularExpression
regularExpressionWithPattern:@"([\\+\\-][0-9][0-9]):"
options:NSRegularExpressionCaseInsensitive
error:nil];
[lastColonRegex replaceMatchesInString:dateWithoutColonString
options:NSRegularExpressionCaseInsensitive
range:NSMakeRange(0, [dateString length])
withTemplate:@"$1"];