Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone shortdate with 4 digit year

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];
like image 912
Dave Avatar asked May 10 '09 15:05

Dave


2 Answers

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

like image 98
Jason Harwig Avatar answered Oct 27 '22 23:10

Jason Harwig


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...

like image 25
konran Avatar answered Oct 27 '22 22:10

konran