This is ridiculous, isn't it?
Mid-2013, and Apple still hasn't provided an easy way to set the NSDate.
During my current iPad project, I could not believe that I had to stop the performance for a while in order to write my own helper class in order to get the Year value from NSDate. I mean, come on, this is the main material.
Anyway, here is a helper class that I used in my project to convert a string to an NSDate value:
@implementation DateHelper +(NSDate*)parseDateString:(NSString *)dateString { NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init]; [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"MMM dd, yyyy"]; NSDate *theDate = nil; NSError *error = nil; if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) { NSLog(@"Date '%@' could not be parsed: %@", dateString, error); } return theDate; } @end
Using this code, you can set the NSDate value using something like:
NSDate* date = [DateHelper parseDateString:@"Jul 16, 2013"];
Note. This function was based on the code taken here: stack overflow
My solution was to use the following code, but I found that sometimes it just didn't understand and returned zero.
I remember that it failed miserably on October 12, 2012 ... that's why I gave up and used the more complex parseDateString function shown above.
My point is ... be careful.
Some of the very simple NSDate functions just don't work properly ...
Mike Gledhill Jul 18 '13 at 14:17 2013-07-18 14:17
source share