PgmFreek
PgmFreek

Reputation: 6402

NSDate from NSString

I have a string of the format @"Jan 3rd, 2011 4:55am". Can any one please tell me to convert above string to NSDate using NSDateFormatter?

Upvotes: 2

Views: 638

Answers (1)

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

Here is how I would do it:

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

[format setDateFormat:@"MMM d, yyyy h:mm a"];
NSString *strDate = @"Jan 3rd, 2011 4:55 am";
removeUnwantedCharactersFromDateString(&strDate);
NSDate *date = [format dateFromString:strDate];

[format release];

And the removeUnwantedCharactersFromDateString function (I am the king of pointlessly long names :) )

void removeUnwantedCharactersFromDateString(NSString **str)
{
    NSString *str1 = *str;
    NSRange seekrange = NSMakeRange(5, [str1 rangeOfString:@","].location - 5);

    NSRange range = [str1 rangeOfString:@"st" options:NSCaseInsensitiveSearch range:seekrange];
    if (range.location != NSNotFound)
        goto END;
    range = [str1 rangeOfString:@"nd" options:NSCaseInsensitiveSearch range:seekrange];
    if (range.location != NSNotFound)
        goto END;

    range = [str1 rangeOfString:@"rd" options:NSCaseInsensitiveSearch range:seekrange];
    if (range.location != NSNotFound)
        goto END;

    range = [str1 rangeOfString:@"th" options:NSCaseInsensitiveSearch range:seekrange];
    if (range.location == NSNotFound)
    {
        [NSException raise:@"Invalid operation" format:@"The string is in the incorrect format"];
        return;
    }

END:
    *str = [str1 stringByReplacingCharactersInRange:range withString:@""];
}

Lots of help from here:

http://www.stepcase.com/blog/2008/12/02/format-string-for-the-iphone-nsdateformatter/

Upvotes: 1

Related Questions