I am sure I am just missing something. But I have googled this for days trying to find how to show a 4 digit year when displaying an NSDate with a style of NSDateFormatterShortStyle. Please let me know if you have a solution. Here is the code I am using now.
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
// add label for birth
UILabel *birthday = [[UILabel alloc] initWithFrame:CGRectMake(125, 10, 100, 25)];
birthday.textAlignment = UITextAlignmentRight;
birthday.tag = kLabelTag;
birthday.font = [UIFont boldSystemFontOfSize:14];
birthday.textColor = [UIColor grayColor];
birthday.text = [dateFormatter stringFromDate:p.Birth];
If you need four digit years, set the dateformat:
using the exact format you'd like. The downside is you lose automatic locale formatting.
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
...
birthday.text = [dateFormatter stringFromDate:p.Birth];
If you need localization then you could try modifying the date format of the short style.
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
if ([[dateFormatter dateFormat] rangeOfString:@"yyyy"].location == NSNotFound) {
NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:@"yy" withString:@"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
Updated with Bugfix from Max Macleod
Just in case that someone stumbles in here as I did 'cos I needed such a thing with a 2 digit year in a localized date format and this is a really old question, here is my solution:
NSLocale* curLocale = [NSLocale currentLocale];
NSString* dateFmt = [NSDateFormatter dateFormatFromTemplate: @"ddMMyyyy"
options: 0
locale: curLocale];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:dateFmt];
NSString* retText = [formatter stringFromDate:refDate];
return retText;
Maybe someone could use it sometime...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With