I’ve written a method as a category on NSDate which returns a string from a date. The format is {four year digits}{two month digits}{two day digits}. For some reason, the formatter returns the current year as the four year digits instead of returning the year of the date. Here’s my code:
- (NSString *) YYYYMMDD{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setDateFormat:@"YYYYMMdd"]; // This line is doing something odd, not sure why yet.
NSString *dateAsString = [formatter stringFromDate:self];
NSLog(@"Date: %@ String: %@", [self description], dateAsString);
return dateAsString;
}
Looking at the line that is logged, you’ll notice that the year is inflexible and sticks to the current year, even if the year which should be represented by the date object isn’t the current year.
Any idea why this is? Am I using an incorrect formatter?
As mentioned in a comment in the Data Formatting Guide:
So try: