Hello,

I am creating NSDateFormatter programmatically, and I wish to parse any type of date string within the user's locale -- for instance "03/13/08" or "1:30PM March 13, 2008" would both be acceptable.

Unfortunately, NSDateFormatter seems to parse only one specific format at a time. I wrote a category method on NSDateFormatter which does the following, and seems to work okay:

// Note: I've set the locale, calendar, and timezone to "current" in the calling code...

-(NSDate*)iterativeDateFromString:(NSString*)string
{ // Iterate through increasingly specific date and time styles, finding one that parses.
        NSDate* theBestDate = nil;
        int timeStyle, dateStyle;
for (timeStyle = NSDateFormatterNoStyle; timeStyle <= NSDateFormatterFullStyle; timeStyle++)
        {
for (dateStyle = NSDateFormatterNoStyle; dateStyle <= NSDateFormatterFullStyle; dateStyle++)
                {
                        NSDate* aDate = nil;
                        [self setTimeStyle:(NSDateFormatterStyle)timeStyle];
                        [self setDateStyle:(NSDateFormatterStyle)dateStyle];
                        NSRange r = NSMakeRange(0, [string length]);
                        NSError* err = nil;
if ([self getObjectValue:&aDate forString:string range:&r error:&err])
                                theBestDate = aDate;
                }
        }
        return theBestDate;
}

But it seems there's got to be a better way to do this. Any ideas?

Joe K.
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to