• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Parsing any date/time format with NSDateFomatter
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Prev by Date: Re: Converting NSString to valid HTML string
  • Next by Date: Re: !foo vs foo == nil
  • Previous by thread: Re: Converting NSString to valid HTML string
  • Next by thread: Scaling an NSImage makes the edges disappear.
  • Index(es):
    • Date
    • Thread