Friday, May 6, 2011

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];
From stackoverflow
  • kCFDateFormatterShortStyle Specifies a short style, typically numeric only, such as “11/23/37” or “3:30pm”.

    Available in Mac OS X v10.3 and later.

    Declared in CFDateFormatter.h.

    Source

    NSDateFormatterShortStyle doesn't appear to give you 4 digit years.

    Dave : this is kind of my point. there is no format that is month/day/year that gives 4 digit years. if i put in a format, i lose localization. this is my frustration.
  • 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 sort style.

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:@"yy" withString:"yyyy"]
    [dateFormatter setDateFormat:fourDigitYearFormat];
    
    Dave : thanks but I need it localized

0 comments:

Post a Comment