4

I'm trying to use only a NSDateFormatter to format string representation of a date/time to an NSDate object. The issue is that I can't figure out how to allow the ordinal suffixes in the format.

So lets say I have a string "Wednesday, August 11th 2010 8:00 PM"

What one line NSDate dateFormat should I use?

Like "EEEE, MMM dd'th' yyyy h:mm a" would work, but that will only work for ordinal days ending in 'th', whereas i need a single format that will allow for 1st, 2nd, 3rd, 4th 5th etc.

It seems like a wildcard character in the format string to accomplish this. I've tried a few things like: % * ?

psy
  • 2,791
  • 26
  • 26
  • 1
    See this question: http://stackoverflow.com/questions/1283045/ordinal-month-day-suffix-option-for-nsdateformatter-setdateformat – Wevah Aug 12 '10 at 00:31
  • That's for the other way around. NSDate to NSString, i need NSString to NSDate – psy Aug 12 '10 at 03:30
  • Generally, NSDateFormatter gets confused if you try to parse a date containing a day of the week. Best to strip that off and just parse the remainder. – Hot Licks Jul 29 '13 at 14:35

2 Answers2

3

This is apparently not possible with the NSDateFormatter.

psy
  • 2,791
  • 26
  • 26
  • 1
    I'm giving up and manually replacing references of `"st, " "nd, " "rd, " "th, "` with a space character `" "` before sending it through a dateformatter. Makes things a bit more difficult, but it really is the only way since there is no wildcard character..... – rwyland Dec 05 '12 at 07:03
-1

You want to use an NSDateFormatter like so:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setDateStyle: NSDateFormatterLongStyle];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter release];

Either NSDateFormatterLongStyle or NSDateFormatterFullStyle should get you the results you're looking for.

Samuel Goodwin
  • 1,698
  • 13
  • 17
  • I'm looking to pass in a custom string formatter, and not use the ones provided by the SDK. – psy Feb 26 '11 at 04:33
  • 1
    according the docs, setting the date style doesn't help -- can't see any styles that support "1st", "2nd" etc. e.g. the long style just gives "November 23, 1937”. He wants "23rd". – occulus May 31 '11 at 09:09