Friday, May 10, 2013

NSDateFormatter getObjectValue forString range error example ios


getObjectValue forString range error:

Returns by reference a date representation of a given string and the range of the string used, and returns a Boolean value that indicates whether the string could be parsed.
- (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string range:(inout NSRange *)rangep error:(out NSError **)error
Parameters
obj
If the receiver is able to parse string, upon return contains a date representation of string.
string
The string to parse.[NSDateFormatter getObjectValue forString range error]
rangep
If the receiver is able to parse string, upon return contains the range of string used to create the date.
error
If the receiver is unable to create a date by parsing string, upon return contains an NSError object that describes the problem.
Return Value
YES if the receiver can create a date by parsing string, otherwise NO.
Example of [NSDateFormatter getObjectValue forString range error]
NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];
Example of [NSDateFormatter getObjectValue forString range error]
+ (NSDate *)parseRFC3339Date:(NSString *)dateString 
{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

    NSDate *theDate = nil;
    NSError *error = nil; 
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }

    [rfc3339TimestampFormatterWithTimeZone release];
    return theDate;
}
Example of [NSDateFormatter getObjectValue forString range error]
- (NSDate *)dateWithString:(NSString *)string locale:(NSString *)localeIdentifier {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setDateStyle:NSDateFormatterShortStyle];

    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
    [formatter setLocale:locale];
    [locale release];

    NSDate *date = nil;
    NSRange range = NSMakeRange(0, [string length]);
    NSError *error = nil;
    BOOL converted = NO;
    converted = [formatter getObjectValue:&date forString:string range:&range error:&error];
    [formatter release];

    return converted? date : nil;
}