Parsing any date/time format with NSDateFomatter
Parsing any date/time format with NSDateFomatter
- Subject: Parsing any date/time format with NSDateFomatter
- From: Joseph Kelly <email@hidden>
- Date: Thu, 21 Aug 2008 11:35:39 -0700
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 (email@hidden)
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:
This email sent to email@hidden