iphone短缺4位数年份

Dav*_*ave 7 iphone nsdate nsdateformatter

我确信我只是遗漏了一些东西.但是我已经搜索了几天试图找到如何显示一个4位数的年份显示NSDate与NSDateFormatterShortStyle样式.如果您有解决方案,请告诉我.这是我现在使用的代码.

[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];
Run Code Online (Sandbox Code Playgroud)

kon*_*ran 11

以防万一有人偶然发现我在这里'因为我需要这样一个2位数年份的本地化日期格式,这是一个非常古老的问题,这是我的解决方案:

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;
Run Code Online (Sandbox Code Playgroud)

也许有人可以在某个时候使用它......


Jas*_*wig 10

如果您需要四位数年份,请dateformat:使用您想要的确切格式.缺点是你失去了自动语言环境格式.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

...

birthday.text = [dateFormatter stringFromDate:p.Birth];
Run Code Online (Sandbox Code Playgroud)

如果您需要本地化,那么您可以尝试修改短样式的日期格式.

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];             
}
Run Code Online (Sandbox Code Playgroud)

更新了Max Macleod的Bugfix